Printing correct time using timezones, Python

ε祈祈猫儿з 提交于 2019-12-05 02:06:25

.replace does no computation: it simply replaces one or more field in the new returned object, while copying all others from the object it's called on.

If I understand your situation correctly, you start with a datetime object which you know (through other means) is UTC, but doesn't know that itself (is has a tzinfo attribute of None, meaning "I'm totally clueless regarding what timezone I'm in).

So, first, you make a timezone-aware from your input timezone-naive object, in order to inform it that it's in timezone UTC (all other fields just get copied over):

aware = naive.replace(tzinfo=utc)

Then, you can request computations regarding timezones, and printing in consequence:

print aware.astimezone(Pacific).strftime('%a %b %d %X %z')

With dt.replace(tzinfo=tz) you're not really converting the time value, you're just saying 'hey no, wait, this time was actually in PDT, not in UTC'. You'll probably want to use datetime.astimezone(tz) instead.

Mark Ransom

I think Wim had the right idea, just backwards. If you want to know what your time would be in UTC, use:

print pst.astimezone(UTC).strftime( "%a %b %d %X" )

You'll have to dig up a definition for a UTC timezone class. I understand why Python didn't want to supply a default implementation of every possible tzinfo, but UTC should have been included in the base package.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!