Explanation of Python3 Time Stamp Conversion to Date in Specified Format

  • 2021-10-24 23:13:52
  • OfStack

When writing Python, we often encounter the problem of time format, first of all, the conversion between the recently used timestamp (timestamp) and the time string. The so-called timestamp is the number of seconds from 00:00 on January 1, 1970 to the present. It turns out that I also wrote about how to convert time in python3.

In Python, the timestamp can be obtained by the time () method in the time module, such as:


import time
timestamp = time.time()
print(timestamp)

Output:

1551077515.952753

This number can be understood as follows: before the decimal point is the number of seconds from 00:00 on January 1, 1970 to the present, and after the decimal point is the count of microseconds.

This timestamp is not easy to remember and understand, so we hope to convert it into an easy-to-understand time format, and the timestamp is converted into a date in a specified format. The commonly used modules are time and datetime.

Method 1: Use the time module


import time
timeStamp = 1551077515
timeArray = time.localtime(timeStamp)
formatTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print (formatTime)

Results:

2019-02-25 14:51:55

Method 2: Use the datetime module


import datetime
timeStamp = 1551077515
timeArray = datetime.datetime.utcfromtimestamp(timeStamp)
formatTime = timeArray.strftime("%Y-%m-%d %H:%M:%S")
print (formatTime)

Results:

2019-02-25 14:51:55

The results are completely identical. Here, time and datetime can convert timestamps into specified time formats, but they are still different. Generally speaking, time is lower than datetime.

The date on which the time stamp of Python time conversion is converted to the specified format is over. For more information on Python time conversion methods, please see the related links below


Related articles: