convert time string XhYmZs to seconds in python
I have a string which comes in three forms:
XhYmZs or YmZs or Zs
where, h,m,s are for hours, mins, secs and X,Y,Z are the corresponding values.
How do I efficiently convert these strings to seconds in python2.7?
I guess I can do something like:
s="XhYmZs" if "h" in s: hours=s.split("h") elif "m" in s: mins=s.split("m")[-1]
... but this does not seem very efficient to me :(
Split on the delimiters you're interested in, then parse each resulting element into an integer and multiply as needed:
import re def hms(s): l = list(map(int, re.split('[hms]', s)[:-1])) if len(l) == 3: return l*3600 + l*60 + l elif len(l) == 2: return l*60 + l else: return l
This produces a duration normalized to seconds.
>>> hms('3h4m5s') 11045 >>> 3*3600+4*60+5 11045 >>> hms('70m5s') 4205 >>> 70*60+5 4205 >>> hms('300s') 300
You can also make this one line by turning the
re.split() result around and multiplying by 60 raised to an incrementing power based on the element's position in the list:
def hms2(s): return sum(int(x)*60**i for i,x in enumerate(re.split('[hms]', s)[-2::-1]))
Split on the delimiters you're interested in, then parse each resulting element into an integer and multiply as needed: import re def hms(s): l XhYmZs or YmZs or Zs where, h,m,s are for hours, mins, secs and X,Y,Z are the corresponding values. How do I efficiently convert these strings to seconds in python2.7?
>>> import datetime >>> datetime.datetime.strptime('3h4m5s', '%Hh%Mm%Ss').time() datetime.time(3, 4, 5)
Since it varies which fields are in your strings, you may have to build a matching format string.
>>> def parse(s): ... fmt=''.join('%'+c.upper()+c for c in 'hms' if c in s) ... return datetime.datetime.strptime(s, fmt).time()
The datetime module is the standard library way to handle times.
Asking to do this "efficiently" is a bit of a fool's errand. String parsing in an interpreted language isn't fast; aim for clarity. In addition, seeming efficient isn't very meaningful; either analyze the algorithm or benchmark, otherwise it's speculation.
How to convert a time string to seconds in Python. time_string = "01:01:09" date_time = datetime. datetime. strptime(time_string, "%H:%M:%S") print(date_time) a_timedelta = date_time - datetime. datetime(1900, 1, 1) seconds = a_timedelta. total_seconds() print(seconds) Python Server Side Programming Programming If you have a function that returns information in seconds, but you need that information in hours:minutes:seconds format, you can use the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical
Do not know how efficient this is, but this is how I would do it:
import re test_data = [ '1h2m3s', '1m2s', '1s', '3s1h2m', ] HMS_REGEX = re.compile('^(\d+)h(\d+)m(\d+)s$') MS_REGEX = re.compile('^(\d+)m(\d+)s$') S_REGEX = re.compile('^(\d+)s$') def total_seconds(hms_string): found = HMS_REGEX.match(hms_string) if found: x = found.group(1) return 3600 * int(found.group(1)) + \ 60 * int(found.group(2)) + \ int(found.group(3)) found = MS_REGEX.match(hms_string) if found: return 60 * int(found.group(1)) + int(found.group(2)) found = S_REGEX.match(hms_string) if found: return int(found.group(1)) raise ValueError('Could not convert ' + hms_string) for datum in test_data: try: print(total_seconds(datum)) except ValueError as exc: print(exc)
or going to a single match and riffing on TigerhawkT3's one liner, but retaining the error checking of non-matching strings:
HMS_REGEX = re.compile('^(\d+)h(\d+)m(\d+)s$|^(\d+)m(\d+)s$|^(\d+)s$') def total_seconds(hms_string): found = HMS_REGEX.match(hms_string) if found: return sum( int(x or 0) * 60 ** i for i, x in enumerate( (y for y in reversed(found.groups()) if y is not None)) raise ValueError('Could not convert ' + hms_string)
A minute is converted to 60 seconds. An hour is converted to 3600 seconds. String representations of timedelta objects are normalized similarly to their Thankfully, Python comes with the built-in module datetime for dealing with dates and times. It comes with various functions for manipulating dates and times. Using this module, we can easily parse any date-time string and convert it to a datetime object. Converting Strings using datetime. The datetime module consists of three different object
My fellow pythonistas, please stop using regular expression for everything. Regular Expression is not needed for such simple tasks. Python is considered a slow language not because the GIL or the interpreter, because such mis-usage.
In : import re ...: def hms(s): ...: l = list(map(int, re.split('[hms]', s)[:-1])) ...: if len(l) == 3: ...: return l*3600 + l*60 + l ...: elif len(l) == 2: ...: return l*60 + l ...: else: ...: return l In : %timeit hms("6h7m8s") 5.62 µs ± 722 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In : def ehms(s): ...: bases=dict(h=3600, m=60, s=1) ...: secs = 0 ...: num = 0 ...: for c in s: ...: if c.isdigit(): ...: num = num * 10 + int(c) ...: else: ...: secs += bases[c] * num ...: num = 0 ...: return secs In : %timeit ehms("6h7m8s") 2.07 µs ± 70.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In : %timeit hms("8s") 2.35 µs ± 124 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In : %timeit ehms("8s") 1.06 µs ± 118 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In : bases=dict(h=3600, m=60, s=1) In : a = ord('a') In : def eehms(s): ...: secs = 0 ...: num = 0 ...: for c in s: ...: if c.isdigit(): ...: num = num * 10 + ord(c) - a ...: else: ...: secs += bases[c] * num ...: num = 0 ...: return secs In : %timeit eehms("6h7m8s") 1.45 µs ± 30 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
see, almost 4 times as fast.
E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second. Convert a time expressed in seconds since the epoch to a string representing local Datetime module provides timedelta object which represents a duration, the difference between two dates or times. datetime.timedelta can be used to represent seconds into hours, minutes and seconds format. # Python Program to Convert seconds. # into hours, minutes and seconds. import datetime. def convert (n):
There's a library python-dateutil -
pip install python-dateutil, it takes a string and returns a
It can parse values as
0.5h - with spaces or without.
from datetime import datetime from dateutil import parser time = '5h15m50s' midnight_plus_time = parser.parse(time) midnight: datetime = datetime.combine(datetime.today(), datetime.min.time()) timedelta = midnight_plus_time - midnight print(timedelta.seconds) # 18950
It can't parse more than 24h at once though.
Convert a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time () is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm () for the inverse of this function.
Notably missing from this page are the capabilities of the Python datetime module, which was introduced in 2.3 and is very powerful. Python. seconds since the "Epoch". time.time(). tuple. time.gmtime(). string Converting Between Formats. Welcome to my new Python Convert String To Datetime tutorial. In this post we will learn how to convert string into datetime object in python. But to understand this concept, firstly we will have to learn some basic information about datetime object in python, So let’s start. The concept of dealing with datetime is ridiculously simple in python.
E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second. Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 8.1. datetime — Basic date and time types¶. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Using this module, we can easily parse any date-time string and convert it to a datetime of the date-time and the second one is the format of the input string. ISO 8601 string to Date. Convert an ISO 8601 date string ("YYYY-MM-DD") into a Date object. Solution: Read it into a Datetime using strptime() then build a new Date object from that. Example: read the string "2019-10-20" into a Date object
- It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the FAQ and How to Ask.
- Do you mean that YmZs is something like 3m5s?
- @StephenRauch: yes, that is correct.
- @TigerhawkT3: I do not agree with you that I want users to write code for me. I am just practicing with python, and as you can see I have clearly mentioned how to
efficientlywrite such a code. Ofcourse, I can use a string split and split them into
intsby looking or regexing for h,m,s - but I do not think this is efficient.
- So, you not only want free code, you want efficient free code?
- This is so cool.. Wonder why I could not think of it :( Accepted the answer.. Thanks again and sorry if my question was a bit sparse the first time around - I was getting frustrated not able to think of a quick solution for this. urgh!
- The original code is better for someone like me - I can then see what is going on :)
- "String parsing in an interpreted language isn't fast" - It can be quite fast, particularly in a language meant for it, like Perl.
- It's all relative; Perl inherits it from ed and awk, which are both written in C specifically for text processing. Python does provide regex parsing at the same level, but tends to lose some when people slice strings as it copies (buffers can avoid that). When you compare to Micron Automata, all software is slow. If performance really is a concern here, it's higly likely that a system approach is better; for instance, does it really need to be parsed into time, or is it enough to have a comparison function?
- Thanks Stephen. I will go for @TigerHawks solution. Looks more clean.
- @AJW - Yes, he is very smart, but kinda cranky... You could still upvote my submission. :-)