Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to seconds [duplicate]

Tags:

python

I am looking for python equivalent GNU date(1) option. Basically I want to convert date into seconds like in the example below, I tried look from the python docs but I couldn't find equivalent time module.

$ convdate="Jul  1 12:00:00 2015 GMT"

$ date '+%s' --date "$convdate"

1435752000

From GNU date(1) man page

-d, --date=STRING
              display time described by STRING, not 'now'
like image 922
mobu Avatar asked Dec 19 '22 23:12

mobu


2 Answers

AS far as I understand, UNIX represents the dates as the offset from Jan 1, 1970, so in order to do that in python you could get the time delta. In particular for your example:

from datetime import datetime
a = datetime.strptime(convdate, "%b %d %H:%M:%S %Y %Z")
b = datetime(1970, 1, 1)
(a-b).total_seconds()

The output is

1435752000.0

like image 119
Mariano Anaya Avatar answered Dec 30 '22 22:12

Mariano Anaya


>>> x = datetime.strptime('Jul 1 12:00:00 2015 GMT', '%b %d %H:%M:%S %Y %Z')
>>> x.timestamp()
1435744800.0

Note that this is a local timestamp. My timezone is UTC+2, hence this is 2 hours less than what you expect. If you want a UTC-based timestamp, you can do this:

>>> from datetime import timezone
>>> x.replace(tzinfo=timezone.utc).timestamp()
1435752000.0
like image 33
poke Avatar answered Dec 30 '22 22:12

poke