简体   繁体   English

在python中,如何将特定本地时间(不是本地时间)中的日期时间转换为UTC

[英]In python how do I convert a datetime in a specific local time (not my local) to UTC

I'm pulling data from a London based service and they are giving me date&time info in London local time.So UTC in winter and BST(UTC+1) in summer. 我正在从伦敦的服务中提取数据,他们会给我伦敦本地时间的日期和时间信息,所以冬天是UTC,夏天是BST(UTC + 1)。

Internally we use UTC for everything, in Python how do I convert the London stuff to UTC in a way that will account for daylight savings? 在内部,我们使用UTC进行所有操作,在Python中如何将伦敦的东西转换为UTC,以节省日光?

I appreciate that some times around the DST rollover are ambiguous, that's acceptable as long as it works the rest of the year. 我很欣赏DST过渡期间的某些时间模棱两可,只要在今年余下时间都可以使用,这是可以接受的。

For completeness, I'm getting the following info from them: 为了完整起见,我从他们那里得到以下信息:

dt="2012-10-12T19:30:00"
lcnid="LDN"
locale="en-gb"

You need to use a timezone object; 您需要使用时区对象; these don't come with Python itself as the data changes too often. 这些都不是Python本身附带的,因为数据经常更改。 The pytz library is easily installed though. pytz很容易安装。

Example conversion: 转换示例:

>>> import pytz
>>> import datetime
>>> bst = pytz.timezone('Europe/London')
>>> dt = datetime.datetime.strptime('2012-10-12T19:30:00', '%Y-%m-%dT%H:%M:%S')
>>> dt
datetime.datetime(2012, 10, 12, 19, 30)
>>> bst.localize(dt)
datetime.datetime(2012, 10, 12, 19, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)
>>> bst.localize(dt).astimezone(pytz.utc)
datetime.datetime(2012, 10, 12, 18, 30, tzinfo=<UTC>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM