4

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'
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
mobu
  • 497
  • 3
  • 6
  • 11

4 Answers4

6

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

Mariano Anaya
  • 1,126
  • 9
  • 11
3
>>> 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
poke
  • 339,995
  • 66
  • 523
  • 574
1

The conversion you a trying to is is called "seconds since epoch" and is calculated using a function like this one:

def unix_time(dt):
    epoch = datetime.datetime.utcfromtimestamp(0)
    delta = dt - epoch
    return delta.total_seconds()

You can load the datetime directly with each part of the date or load it from a string and calculate the number of seconds:

>>> def unix_time(dt):
...     epoch = datetime.datetime.utcfromtimestamp(0)
...     delta = dt - epoch
...     return delta.total_seconds()
...
>>> import datetime
>>> a = datetime.datetime(2015, 07, 01, 12, 00, 00)
>>> print a
2015-07-01 12:00:00
>>> print unix_time(a)
1435752000.0
>>>

NOTE: you can use long(unix_time(a)) if you want to get rid of the last .0

Hope it helps!

Sergio Ayestarán
  • 5,231
  • 3
  • 35
  • 60
1

mktime can be used to calculate the entered time in secs:

>>> import time
>>> m = time.localtime()#store it in a var 
>>> time.mktime(m)
o/p: 1435657461.0
ZygD
  • 10,844
  • 36
  • 65
  • 84
Sanyal
  • 816
  • 9
  • 22