将unix时间戳字符串转换为可读日期的Python程序
在本文中,我们将看到 Unix 时间戳字符串到可读日期的转换。这可以在fromtimestamp()和strftime()函数的帮助下完成。
使用的功能
fromtimestamp(): fromtimestamp()函数用于返回指定时间戳对应的日期和时间。
注意:这里的时间戳范围从 1970 年到 2038 年,如果时间戳中存在闰秒,则此函数不考虑闰秒。这个函数是一个类方法。
Syntax: @classmethod fromtimestamp(timestamp)
Parameters: This function accepts a parameter which is illustrated below:
- timestamp: This is the specified timestamp for which the date is going to be returned.
Return values: This function returns the date and time corresponding to a specified timestamp.
strftime(): strftime()函数用于将日期和时间对象转换为其字符串表示形式。它接受一个或多个格式化代码的输入并返回字符串表示。
Syntax: strftime(format)
Parameter: This function accepts a single parameter which is illustrated below:
- format: This is the specified date and time object.
Return Values: It returns the string representation of the date or time object.
让我们看看将指定的 Unix 时间戳字符串转换为可读日期的示例
示例 1:转换指定的 Unix 时间戳字符串。
Python
# Python program to illustrate the
# convertion of unix timestamp string
# to its readable date
# Importing datetime module
import datetime
# Calling the fromtimestamp() function to
# extract datetime from the given timestamp
# Calling the strftime() function to convert
# the extracted datetime into its string format
print(datetime.datetime.fromtimestamp(int("1294113662"))
.strftime('%Y-%m-%d %H:%M:%S'))
Python
# Python program to illustrate the
# convertion of unix timestamp string
# to its readable date
# Importing datetime module
import datetime
# Calling the fromtimestamp() function to
# extract datetime from the given timestamp
timestamp = datetime.datetime.fromtimestamp(1200001234)
# Calling the strftime() function to convert
# the extracted datetime into its string format
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
输出:
2011-01-04 04:01:02
示例 2:转换指定的 Unix 时间戳字符串。
Python
# Python program to illustrate the
# convertion of unix timestamp string
# to its readable date
# Importing datetime module
import datetime
# Calling the fromtimestamp() function to
# extract datetime from the given timestamp
timestamp = datetime.datetime.fromtimestamp(1200001234)
# Calling the strftime() function to convert
# the extracted datetime into its string format
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
输出:
2008-01-10 21:40:34