如何在本地时区打印日期时间? [英] How do I print a datetime in the local timezone?

查看:27
本文介绍了如何在本地时区打印日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a variable t that's set to this:

datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)

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

'2009-07-10 18:44:59.193982+00:00'

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

How can I get a similar string, except printed in the local timezone rather than UTC?

推荐答案

认为你应该环顾四周:datetime.astimezone()

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

另请参阅 pytz 模块 - 它非常易于使用 - 例如:

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

示例:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

这篇关于如何在本地时区打印日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆