11

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?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

3 Answers3

23

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
  • 462,703
  • 120
  • 1,088
  • 1,195
11
>>> tt = datetime.datetime( 2013, 8, 15, 6, 0, 0 )
>>> print int(tt.strftime('%s'))
1376535600
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
10

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,425
  • 6
  • 52
  • 68
  • 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