Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 320
om-nom-nom Avatar asked Aug 22 '13 14:08

om-nom-nom


People also ask

How do you convert human readable time to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How do I convert date to epoch time manually?

Epoch Time Difference FormulaMultiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.

How do you calculate epoch time?

POSIX defines that you can deduce the number of days since The Epoch (1970-01-01 00:00:00Z) by dividing the timestamp by 86400. This deliberately and consciously ignores leap seconds.

Is Unix time the same as epoch?

Unix time is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, excluding leap seconds. This time is named the Unix epoch, because it is the start of the Unix time.


2 Answers

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
like image 51
alecxe Avatar answered Oct 06 '22 04:10

alecxe


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
like image 35
Philippe T. Avatar answered Oct 06 '22 04:10

Philippe T.