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?
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.
To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.
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().
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.
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()
>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With