Python 将日期时间格式转换为秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18269888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert datetime format into seconds
提问by PythonEnthusiast
My date is in the format DD/MM/YYYY HH:MM:SS
, ie 16/08/2013 09:51:43
. How can I convert the date into python seconds using total_seconds()
or using any other python function?
我的日期是格式DD/MM/YYYY HH:MM:SS
,即16/08/2013 09:51:43
. 如何使用total_seconds()
或使用任何其他 python 函数将日期转换为 python 秒?
采纳答案by alecxe
Here's how you can do it:
您可以这样做:
>>> from datetime import datetime
>>> import time
>>> s = "16/08/2013 09:51:43"
>>> d = datetime.strptime(s, "%d/%m/%Y %H:%M:%S")
>>> time.mktime(d.timetuple())
1376632303.0
Also see Python Create unix timestamp five minutes in the future.
回答by Adem ?zta?
>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
回答by Jiri
Seconds since when?
从什么时候开始几秒?
See this code for general second computation:
有关一般第二次计算,请参阅此代码:
from datetime import datetime
since = datetime( 1970, 8, 15, 6, 0, 0 )
mytime = datetime( 2013, 6, 11, 6, 0, 0 )
diff_seconds = (mytime-since).total_seconds()
UPDATE: if you need unix timestamp (i.e. seconds since 1970-01-01) you can use the language default value for timestamp of 0 (thanks to comment by J.F. Sebastian):
更新:如果您需要 unix 时间戳(即自 1970-01-01 以来的秒数),您可以使用时间戳为 0 的语言默认值(感谢 JF Sebastian 的评论):
from datetime import datetime
mytime = datetime( 2013, 6, 11, 6, 0, 0 )
diff_seconds = (mytime-datetime.fromtimestamp(0)).total_seconds()