如何在Python中规范化字符串到日期时间格式

时间:2012-11-17 05:53:15

标签: python datetime

我想将日期字符串转换为python datetime格式。字符串如下:

Mon, 26 Dec 2011 20:42:08 +0200
Sat, 24 Dec 2011 16:28:59 +0200

有没有更快的方法将字符串转换为python datetime格式而不使用pytz API?

3 个答案:

答案 0 :(得分:2)

>>> import datetime
>>> s = "Mon, 26 Dec 2011 20:42:08 +0200"
>>> t = datetime.datetime.strptime(s, "%a, %d %b %Y %H:%M:%S %z")
>>> t
datetime.datetime(2011, 12, 26, 20, 42, 8, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

有关日期时间占位符的完整列表,请参阅the docs

答案 1 :(得分:2)

这是一个适用于Python 2.5 +,PyPy,Jython的变种:

from datetime import datetime, timedelta
from email.utils import mktime_tz, parsedate_tz

s = "Mon, 26 Dec 2011 20:42:08 +0200"
t = parsedate_tz(s)
if t[9] is not None:
    utc_offset = timedelta(seconds=t[9])  # local = utc + offset
    print("utc offset: %s" % (utc_offset,))
print(repr(datetime.utcfromtimestamp(mktime_tz(t))))  # naive datetime in UTC

输出

utc offset: 2:00:00  
datetime.datetime(2011, 12, 26, 18, 42, 8)

答案 2 :(得分:1)

试试这个? 假设输入2016-01-02并且您想要标准化所有日期。

def NormalizaData(input):
 input = str(input)
 num = input.split('-')
 year = num[0]
 newnum = num[1]
 num = newnum.split('-')
 month = num[0]
 day = '01'
 return (year + '-' + month + '-' + day)