我有这种格式的日期Thu, 18 Feb 2016 15:33:10 +0200
我希望它们转换为2016-02-12 08:39:09.653475
如何使用Python的标准库实现这一目标?
答案 0 :(得分:3)
您可以使用datetime
模块执行此操作,如下所示:
from datetime import datetime
d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S.%f')
或者在python2中你可以使用:
from datetime import datetime
from dateutil.parser import parse
d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strftime(parse(d), '%Y-%m-%d %H:%M:%S.%f')
或者如果需要坚持使用标准库,请查看J.F.Sebastian在How to parse dates with -0400 timezone string in python?的评论
答案 1 :(得分:0)
点击此链接How to print date in a regular format in Python?
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
这将打印出类似这样的内容:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
答案 2 :(得分:0)
要仅使用stdlib解析输入日期格式,您可以使用email.utils
包:
>>> from datetime import datetime, timedelta
>>> from email.utils import parsedate_tz, mktime_tz
>>> timestamp = mktime_tz(parsedate_tz('Thu, 18 Feb 2016 15:33:10 +0200'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> str(utc_time)
'2016-02-18 13:33:10'
其中str(dt)
相当于dt.isoformat(' ')
。
如果你需要支持闰秒; (假设您的平台支持它们)使用tt = time.gmtime(timestamp)
和time.strftime('%Y-%m-%d %H:%M:%S', tt)
。注意:time.gmtime()
可能在不同平台上有不同的限制(可能小于datetime
的限制。)