Convert datetime format into seconds [duplicate]

2020-07-10 10:19发布

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?

3条回答
何必那么认真
2楼-- · 2020-07-10 10:55
>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
查看更多
走好不送
3楼-- · 2020-07-10 11:15

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.

查看更多
家丑人穷心不美
4楼-- · 2020-07-10 11:16

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):

from datetime import datetime
mytime = datetime( 2013, 6, 11, 6, 0, 0 )
diff_seconds = (mytime-datetime.fromtimestamp(0)).total_seconds()
查看更多
登录 后发表回答