How can I convert HH:MM:SS string to UNIX epoch time?

datetime, python, time

Solution

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:

- Python Create unix timestamp five minutes in the future

Problem

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.

Original source

Related problems