假设我有一个变量t,它设置为:
datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)如果我说str(t),我会得到:
'2009-07-10 18:44:59.193982+00:00'除了在本地时区而不是UTC中打印之外,我如何获得类似的字符串?
发布于 2013-09-15 20:21:39
我使用了这个函数datetime_to_local_timezone(),它看起来非常复杂,但我发现没有更简单的函数版本可以将datetime实例转换为操作系统中配置的本地时区,其中包含当时有效的UTC偏移
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))此示例打印四个日期。对于两个时刻,一个在2009年1月,一个在2009年7月,它以UTC和本地时区分别打印一次时间戳。这里,冬季使用CET (UTC+01:00),夏季使用CEST (UTC+02:00),它打印以下内容:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00https://stackoverflow.com/questions/1111317
复制相似问题