首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在本地时区中打印日期时间?

如何在本地时区中打印日期时间?
EN

Stack Overflow用户
提问于 2009-07-10 18:51:00
回答 6查看 137.9K关注 0票数 46

假设我有一个变量t,它设置为:

代码语言:javascript
运行
复制
datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)

如果我说str(t),我会得到:

代码语言:javascript
运行
复制
'2009-07-10 18:44:59.193982+00:00'

除了在本地时区而不是UTC中打印之外,我如何获得类似的字符串?

EN

Stack Overflow用户

发布于 2013-09-15 20:21:39

我使用了这个函数datetime_to_local_timezone(),它看起来非常复杂,但我发现没有更简单的函数版本可以将datetime实例转换为操作系统中配置的本地时区,其中包含当时有效的UTC偏移

代码语言:javascript
运行
复制
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),它打印以下内容:

代码语言:javascript
运行
复制
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:00
票数 0
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1111317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档