Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime format into seconds [duplicate]

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?

like image 672
PythonEnthusiast Avatar asked Aug 16 '13 09:08

PythonEnthusiast


People also ask

How do I convert datetime to seconds?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How do you convert Timedelta to seconds?

To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.

How do you convert datetime to epoch in Python?

Using strftime() to convert Python datetime to epoch strftime() is used to convert string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime().


3 Answers

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.

like image 122
alecxe Avatar answered Sep 20 '22 18:09

alecxe


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()
like image 41
Jiri Avatar answered Sep 19 '22 18:09

Jiri


>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
like image 24
Adem Öztaş Avatar answered Sep 21 '22 18:09

Adem Öztaş