在python中,如何将特定本地时间(而非本地时间)中的日期时间转换为UTC [英] In python how do I convert a datetime in a specific local time (not my local) to UTC

查看:240
本文介绍了在python中,如何将特定本地时间(而非本地时间)中的日期时间转换为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从伦敦的一家服务中提取数据,他们在给我伦敦本地时间的日期和时间信息。所以冬天是UTC,夏天是BST(UTC + 1)。

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进行所有操作,在Python中如何将伦敦的东西转换为UTC,以解决夏时制?

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?

I请注意,DST过渡周围的某些时间是模棱两可的,只要在一年中的其余时间都可以使用,就可以接受。

I appreciate that some times around the DST rollover are ambiguous, that's acceptable as long as it works the rest of the year.

出于完整性考虑,我从以下信息中获取以下信息:他们:

For completeness, I'm getting the following info from them:

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


推荐答案

您需要使用时区对象;这些都不是Python本身附带的,因为数据经常更改。不过, pytz 易于安装。

You need to use a timezone object; these don't come with Python itself as the data changes too often. The pytz library is easily installed though.

示例转换:

>>> 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>)

这篇关于在python中,如何将特定本地时间(而非本地时间)中的日期时间转换为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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