8

I have a program (sar command line utility) which outputs it's lines with time column. I parse this file with my python script and I would like to convert sar's 02:31:33 PM into epochs e.g. 1377181906 (current year, month and day with hours, minutes and seconds from abovementioned string). How can this done in a less cumbersome way? I tried to do this by myself, but stuck with time/datetime and herd of their methods.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • http://stackoverflow.com/questions/466345/converting-string-into-datetime – Doon Aug 22 '13 at 14:45
  • Not quite the dupe, cause I don't have year/day/month. I **can** use `strptime` but it will initialize missing values to 1 january of 1900 year. I can retrieve missing values by myself and append them to the string, but this lies into *cumbersome* category. – om-nom-nom Aug 22 '13 at 14:48
  • yes, hence the reason I Didn't mark it as dupe/vote to close. Strptime is the way I would do it (I just set the date/time to now, and then parse much like @alecxe is doing.. – Doon Aug 22 '13 at 14:52

2 Answers2

9

Here's one way to do it:

  • read the string into datetime using strptime
  • set year, month, day of the datetime object to current date's year, month and day via replace
  • convert datetime into unix timestamp via calendar.timegm

>>> from datetime import datetime
>>> import calendar
>>> dt = datetime.strptime("02:31:33 PM", "%I:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> calendar.timegm(dt.utctimetuple())
1377138693

Note that in python >= 3.3, you can get the timestamp from a datetime by calling dt.timestamp().

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
4

An another way to have epoch time is to use mktime from time module and pass time tuple of date, so you can do this:

>>> from datetime import datetime
>>> from time import mktime
>>> dt = datetime.strptime("02:31:33 PM", "%H:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> int(mktime(dt.timetuple()))
1377131493
Philippe T.
  • 1,182
  • 7
  • 11