9

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?

PythonEnthusiast
  • 15,691
  • 41
  • 122
  • 238

3 Answers3

21

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.

Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
11
>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
Adem Öztaş
  • 18,635
  • 4
  • 32
  • 41
9

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()
Jiri
  • 16,009
  • 6
  • 50
  • 67
  • 2
    if `mytime` is a local time then you could use `datetime.fromtimestamp(0)` to get `since` value. – jfs Aug 16 '13 at 11:24