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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:50:11  来源:igfitidea点击:

Python Datetime : use strftime() with a timezone-aware date

pythondatetimeutc

提问by snoob dogg

Suppose I have date dlike 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 日期是 20093 月 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

The reason is python actually formatting your datetime object, not some "UTC at this point of time"

原因是 python 实际上格式化了你的 datetime 对象,而不是一些“此时的 UTC”

To show timezone in formatting, use %zor %Z.

要以格式显示时区,请使用%z%Z

Look for strf docsfor details

查找strf 文档以获取详细信息

回答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') )

(http://pytz.sourceforge.net/)

( http://pytz.sourceforge.net/)

回答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