简体   繁体   English

Python:将日期字符串转换为UTC

[英]Python: converting date string to UTC

I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. 我正在使用日期和时间来解析第三方网站HTML,这些日期和时间始终采用英国时间格式,但是源中没有任何时区信息。 Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info? 使用datetime.strptime()将字符串转换为对象很容易,但是如何添加时区信息?

Ultimately, I need to convert these strings to a datetime object in UTC format. 最终,我需要将这些字符串转换为UTC格式的datetime对象。 The code will always run on a PC which is timezone aware, ie datetime.now() will return UK time. 该代码将始终在支持时区的PC上运行,即datetime.now()将返回英国时间。

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')

Is there a nicer way to do this? 有没有更好的方法可以做到这一点?

offset = datetime.now() - datetime.utcnow()
dt -= offset

Use pytz 使用pytz

import datetime
import pytz

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
timezone = pytz.timezone("Etc/Greenwich")
d_aware = timezone.localize(dt)
d_aware.tzinfo
> <DstTzInfo 'Etc/Greenwich' PST-1 day, 16:00:00 STD>
d_aware
datetime.datetime(2017, 12, 7, 13, 30, tzinfo=<StaticTzInfo 'Etc/Greenwich'>)

There are some good libraries that make working with dates so much easier. 有一些很好的库使处理日期变得如此容易。 I like dateparser , parsedatetime , and arrow ; 我喜欢dateparserparsedatetime箭头 ;

import dateparser as dp
dt = dp.parse('07-12-2017 13:30 PST')
print (dt)

dt = dp.parse("Yesterday at 3:00am EST")
print(dt)


2017-07-12 13:30:00-08:00
2017-12-06 17:07:07.557109-05:00

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

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