How to convert the string HH: MM: SS to the UNIX era?

I have a program ( sar command line utility ) that displays its rows with a time column. I am parsing this file with my python script, and I would like to convert sar 02:31:33 PM to an era, for example. 1377181906 (current year, month, and day with hours, minutes, and seconds from the above line). How can this be done in a less cumbersome way? I tried to do this myself, but got stuck with the time / time and herd of my methods.

+6
source share
2 answers

Here is one way to do this:

  • read the string in datetime using strptime
  • set the year, month, day of a datetime object to the current date, month, and day using replace
  • convert datetime to 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 datetime by calling dt.timestamp () .

See also:

+8
source

Another way to have time in the era is to use mktime from a time module and pass in a temporary date tuple 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 
+2
source

Source: https://habr.com/ru/post/952291/


All Articles