5

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
  • 530,221
  • 131
  • 937
  • 1,214
mobu
  • 547
  • 3
  • 6
  • 11

4 Answers4

7

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,246
  • 10
  • 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
  • 369,085
  • 72
  • 557
  • 602
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,590
  • 4
  • 38
  • 62
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
  • 22,092
  • 39
  • 79
  • 102
Sanyal
  • 864
  • 10
  • 22