简体   繁体   English

如何使用python将日期(如“ Apr 15 2014 16:21:16 UTC”)转换为UTC时间

[英]How to convert date like “Apr 15 2014 16:21:16 UTC” to UTC time using python

I have dates in the following format that are used to name zip files: 我有以下格式的日期用于命名zip文件:

Apr 15 2014 16:21:16 UTC

I would like to convert that to UTC numbers using Python. 我想使用Python将其转换为UTC数字。 Does python recognize the 3-character month? python可以识别3个字符的月份吗?

Use: 采用:

import datetime

datetime.datetime.strptime(yourstring, '%b %d %Y %H:%M:%S UTC')

%b is the abbreviated month name. %b是月份的缩写。 By default, Python uses the C (English) locale, regardless of environment variables used. 默认情况下,无论使用什么环境变量,Python都使用C (英语)语言环境。

Demo: 演示:

>>> import datetime
>>> yourstring = 'Apr 15 2014 16:21:16 UTC'
>>> datetime.datetime.strptime(yourstring, '%b %d %Y %H:%M:%S UTC')
datetime.datetime(2014, 4, 15, 16, 21, 16)

The value is timezone neutral, which for UTC timestamps is fine, provided you don't mix local objects into the mix (eg stick to datetime.datetime.utcnow() and similar methods). 该值是时区中性的,如果您不将本地对象混入混合中(例如,坚持使用datetime.datetime.utcnow()和类似方法),则此时间对于UTC时间戳来说是很好的。

An easier way is to use dateutil : 一种更简单的方法是使用dateutil

>>> from dateutil import parser
>>> parser.parse("Apr 15 2014 16:21:16 UTC")
datetime.datetime(2014, 4, 15, 16, 21, 16, tzinfo=tzutc())

Timezone is handled, and it supports other common datetime formats as well. 时区已处理,它也支持其他常见的日期时间格式。

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

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