Python 日期时间:使用具有时区感知日期的 strftime()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48724902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Datetime : use strftime() with a timezone-aware date
提问by snoob dogg
Suppose I have date d
like this :
假设我有这样的约会d
:
>>> d
datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))
As you can see, it is "timezone aware", there is an offset of 2 Hour, utctime is
如您所见,它是“时区感知”,有 2 小时的偏移量,utctime 是
>>> d.utctimetuple()
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19,
tm_hour=23, tm_min=12, tm_sec=0,
tm_wday=6, tm_yday=109, tm_isdst=0)
So, real UTC date is 19th March 2009 23:12:00, right ?
所以,真正的 UTC 日期是 2009年3 月 19 日23:12:00,对吧?
Now I need to format my date in string, I use
现在我需要用字符串格式化我的日期,我使用
>>> d.strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-04-19 21:12:00.000000'
Which doesn't seems to take this offset into account. How to fix that ?
这似乎没有考虑到这个抵消。如何解决?
采纳答案by dnswlt
In addition to what @Slam has already answered:
除了@Slam 已经回答的内容:
If you want to output the UTC time without any offset, you can do
如果你想输出没有任何偏移的UTC时间,你可以这样做
from datetime import timezone, datetime, timedelta
d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2)))
d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
See datetime.astimezonein the Python docs.
请参阅Python 文档中的datetime.astimezone。
回答by Slam
回答by Patrick Artner
This will convert your local time to UTC and print it:
这会将您的本地时间转换为 UTC 并打印出来:
import datetime, pytz
from dateutil.tz.tz import tzoffset
loc = datetime.datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))
print(loc.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S.%f') )
回答by Emmanuel
I couldn't import timezone module (and hadn't much time to know why) so I set TZ environment variable which override the /etc/localtime information
我无法导入 timezone 模块(并且没有太多时间知道为什么)所以我设置了 TZ 环境变量来覆盖 /etc/localtime 信息
>>> import os
>>> import datetime
>>> print datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 11:26
>>> os.environ["TZ"] = "UTC"
>>> print datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
2019-05-17 09:26