python将日期时间格式的字符串转换为秒 [英] python convert datetime formatted string to seconds

查看:492
本文介绍了python将日期时间格式的字符串转换为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串解码为新纪元,但是我很难获取时区。这是Amazon S3密钥的最后修改日期。

I am trying to decode a date string to epoch but I have difficulties getting the timezone. This is the last modified date from Amazon S3 keys.

time.strptime(key.last_modified, '%Y-%m-%dT%H:%M:%S.%Z')

ValueError: time data u'2013-10-20T00:41:32.000Z' 
            does not match format '%Y-%m-%dT%H:%M:%S.%Z'

如果我摆脱工作的时区(.000Z),但我也需要时区。

If I get rid of the timezone (.000Z) it works, but I need the timezone as well.

推荐答案

.000Z 不被识别为时区偏移量。实际上,您有毫秒和一个时区( Z 是UTC),并且正式 time.strptime()解析器无法处理毫秒。在某些平台上,%f 将解析微秒部分,然后丢弃信息。

The .000Z is not recognized as a timezone offset. In fact, you have milliseconds and a timezone (Z is UTC), and officially, time.strptime() parser cannot handle milliseconds. On some platforms %f will parse the microsecond portion, then discard the information.

datetime.datetime.strptime() 类方法,但是,可以,但不是时区;将 Z 解析为文字,它可以正常工作:

The datetime.datetime.strptime() class method, however, can, but not the timezone, however; parse the Z as a literal and it works:

from datetime import datetime

datetime.strptime(key.last_modified, '%Y-%m-%dT%H:%M:%S.%fZ')

演示:

>>> from datetime import datetime
>>> import time
>>> example = u'2013-10-20T00:41:32.000Z'
>>> datetime.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2013, 10, 20, 0, 41, 32)
>>> time.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')
time.struct_time(tm_year=2013, tm_mon=10, tm_mday=20, tm_hour=0, tm_min=41, tm_sec=32, tm_wday=6, tm_yday=293, tm_isdst=-1)

请注意,在我的Mac OS X笔记本电脑上,%f 适用于 time.strptime();

Note that on my Mac OS X laptop, %f works for time.strptime(); it is not guaranteed to work everywhere, however.

datetime.datetime()对象转换为时间元组可以使用 datetime.timetuple( )方法

Converting a datetime.datetime() object to a time tuple can be done with the datetime.timetuple() method.

这篇关于python将日期时间格式的字符串转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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