Python datetime和tzinfo对象(更改分钟而不是小时) [英] Python datetime and tzinfo objects (changing minutes instead of hours)

查看:141
本文介绍了Python datetime和tzinfo对象(更改分钟而不是小时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将tzinfo应用于日期时间对象。

I'm trying to apply a tzinfo to a datetime object.

In [1]: from datetime import datetime
In [2]: import pytz

In [3]: london = pytz.timezone("Europe/London")
In [4]: london
Out[5]: <DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>

In [6]: localized_date_object = datetime(2016, 1, 1, 11, 30, 0, 5000, london)
In [7]: localized_date_object
Out[8]: datetime.datetime(2016, 1, 1, 11, 30, 0, 5000, tzinfo=<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>)

In [9]: utc_date_object = localized_date_object.astimezone(pytz.utc)
In [10]: utc_date_object
Out[11]: datetime.datetime(2016, 1, 1, 11, 31, 0, 5000, tzinfo=<UTC>)

In [16]: paris = pytz.timezone("Europe/Paris")
In [17]: localized_date_object = datetime(2016, 1, 1, 11, 30, 0, 5000, paris)
In [18]: utc_date_object = localized_date_object.astimezone(pytz.utc)
In [19]: utc_date_object
Out[19]: datetime.datetime(2016, 1, 1, 11, 21, 0, 5000, tzinfo=<UTC>)

如您所见,它是对分钟而不是小时应用了增量。

有人可以解释一下我在这里做错什么。

As you can see, it's applying delta to minutes instead of hours.
Can someone explain me what I'm doing wrong here.

推荐答案

我认为您应该使用CE T代表巴黎时间,UTC代表伦敦时间。
我使用的方法略有不同,但对我有用:

I think that you should use CET for Paris time and UTC for London time. I am using a bit different approach but it works for me:

from datetime import datetime
from pytz import timezone

ldo = datetime(2016, 1, 1, 11, 30, 0, 5000)
ldo = ldo.replace(tzinfo=timezone('Europe/London'))

udo = ldo.astimezone(timezone('UTC'))
print ldo
print udo

ldo = datetime(2016, 1, 1, 11, 30, 0, 5000)
ldo = ldo.replace(tzinfo=timezone('CET'))

udo = ldo.astimezone(timezone('UTC'))
print ldo
print udo

更新:

存储时间值时,还应该存储相关的时区信息。 IMO的最佳做法是将所有内容存储在UTC中,然后转换以查看用户时区。从世界标准时间转换为欧洲/巴黎的BTW可以正常工作,请尝试以下操作:

When you store time values there should be also stored related timezone information. IMO best practice is to store everything in UTC and convert for viewing to "user" timezone. BTW converting from UTC to Europe/Paris works flawlessly, try this:

winter = datetime(2016, 1, 1, 11, 30, 0, 5000, tzinfo=timezone("UTC"))
paris =  winter.astimezone(timezone("Europe/Paris"))
print paris
# 2016-01-01 12:30:00.005000+01:00

summer = datetime(2016, 6, 1, 11, 30, 0, 5000, tzinfo=timezone("UTC"))
paris = summer.astimezone(timezone("Europe/Paris"))
print paris
# 2016-06-01 13:30:00.005000+02:00

这篇关于Python datetime和tzinfo对象(更改分钟而不是小时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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