How To Convert Timestamp To Specified Format Date String In Python3

When writing Python code, we often encounter the problem of time format. The first thing is the conversion between timestamp and date time fromat string. The timestamp is the number of seconds from 00:00:00 on January 1, 1970 to the present day. In Python, timestamp can be obtained by the time() method in the time module, such as below source code.

~$ python3
>>> import time
>>> timestamp = time.time()
>>> print(timestamp)

Before the decimal point is the number of seconds from 00:00 on January 1, 1970 to the present, and behind the decimal point is the count of microseconds.

This timestamp is not easy to remember and understand, so we want to convert it into a formatted time string that is easy to understand. The commonly used modules are time and datetime to convert timestamp to a date string in a specified format.

Table of Contents

1. Use time Module.

>>> import time # import time module
>>> timeStamp = time.time()  # specify a timestamp value.

>>> timeArray = time.localtime(timeStamp) # use time module localtime method to convert the timestamp value with local time zone and return a time array.

>>> formatTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) # invoke the time module strftime method to format the time array to a local time string.

>>> print (formatTime) # print out the time string with above format.

2019-03-28 21:17:15

2. Use datetime Module.

>>> import datetime
>>> time_stamp = time.time()

>>> time_array = datetime.datetime.utcfromtimestamp(time_stamp)

>>> format_time = time_array.strftime("%Y-%m-%d %H:%M:%S")

>>> print (format_time)

2019-03-28 13:20:17

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.