有两个部分:
- 将Unix时间戳(“自纪元以来的秒数”)转换为本地时间
- 以所需格式显示本地时间。
一个可移植的方法是使用pytz
时区获取本地时间,即使本地时区在过去有不同的UTC偏移量且Python无法访问时区数据库也可以使用:
#!/usr/bin/env python
from datetime import datetime
import tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone()
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
为了显示它,您可以使用任何您的系统支持的时间格式,例如:
To display it, you could use any time format that is supported by your system e.g.:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
如果您不需要本地时间,则可以获取可读的UTC时间:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
如果您不关心可能会影响返回日期的时区问题,或者Python是否可以访问您系统上的tz数据库:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
在Python 3上,您可以仅使用标准库(如果Python无法访问tz数据库,例如在Windows上,则UTC偏移可能不正确)获取时区感知的日期时间:
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
time
模块中的函数是对应 C API 的简单封装,因此它们可能比相应的 datetime
方法不太可移植,但如果有需要也可以使用它们:
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
import re s = "TheQuickBrownFox" s = re.sub('([A-Z])', r'_\1', s).lower().lstrip('_') print(s)
输出结果为:the_quick_brown_fox - slushy