简体   繁体   English

将字符串转换为纪元时间戳

[英]Convert string to epoch timestamp

I have timestamps in the following format: 我有以下格式的时间戳:

date = Fri Nov 30 13:32:45 UTC 2012

Is there a way to convert this string to an epoch timestamp? 有没有办法将此字符串转换为纪元时间戳? I haven't been able to figure out how to convert this string? 我一直无法弄清楚如何转换此字符串? Here's what I have been trying: 这是我一直在尝试的方法:

import datetime

d = 'Fri Nov 30 13:32:45 UTC 2012'
fmt = '%a %b %e %R %Y'
print d.strftime(fmt)

You missed the timezone directive: 您错过了时区指令:

%Z Time zone name (no characters if no time zone exists). %Z时区名称(如果没有时区,则没有字符)。

You used the wrong "day of the month" directive: 您使用了错误的“月中某天”指令:

%d Day of the month as a decimal number [01,31]. %d月份中的天,以十进制数字[01,31]。

You used the wrong "time" directive: 您使用了错误的“时间”指令:

%X Locale's appropriate time representation. %X语言环境的适当时间表示形式。

Try: 尝试:

>>> import time
>>> d = 'Fri Nov 30 13:32:45 UTC 2012'
>>> fmt = '%a %b %d %X %Z %Y'
>>> epoch = int(time.mktime(time.strptime(d, fmt)))
>>> print epoch
1354278765

You need strptime method of class datetime . 您需要类datetime strptime方法。 And the format you need is %a %b %d %H:%M:%S %Z %Y . 您需要的格式为%a %b %d %H:%M:%S %Z %Y With your example it give : 以您的示例为例:

>>> import datetime
>>> date = "Fri Nov 30 13:32:45 UTC 2012"
>>> fmt = "%a %b %d %H:%M:%S %Z %Y"
>>> d = datetime.datetime.strptime(date, fmt)
>>> d
datetime.datetime(2012, 11, 30, 13, 32, 45)
>>> d.timestamp()
1354278765.0

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

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