Convert string to time format - python

>>> x
['00:05:09.252', '00:05:42.244', '00:06:44.546']
How can I convert these string items to 'hh:mm:ss.uuu' time format, so that I can do time calculations in this format?
I read the docs, but everything seem to be explained in context of datetime and various time zones, while I just wanna do calculation in time format without writting my own function for this task.

given your data is strictly formatted to hour:min:sec.usec
(looks like they don't have directives to deal with microseconds in python strptime, so guess you have to supply the values yourself to datetime.time's constructor)
import datetime
def timeconverter(timestring):
hour, min, sec = timestring.split(':')
sec, usec = sec.split('.')
time = datetime.time(*[int(x, 10) for x in (hour, min, sec, usec)])
return time

Check out strptime in the time module.
import time
t= time.strptime("00:05:42.244", "%H:%M:%S")
Do this if you don't care about the decimal part of the seconds. If you do care then the approuch used by thkang is a better solution.

Related

Python ,Duration Calcution between Timestamps

I'm working on backend ,Short Explanation :
I have 2 timestamps which are in this format "2022-10-29T16:30:00+05:30","2022-10-29T17:30:00+05:30" .I need to calculate this duration between these but I tried to figure out the format of this timestamp,so I could calculate using datetime method in python.
This uses the method datetime.fromisoformat(date_string) to convert the ISO 8601-formatted string into a datetime object. From there, you can subtract to find the time difference. Additionally, you may want to add some code to check for negative results, or you can simply use the function abs(x).
import datetime
def duration_between(ts_1: str, ts_2: str) -> datetime.datetime:
ts_1_dt = datetime.datetime.fromisoformat(ts_1)
ts_2_dt = datetime.datetime.fromisoformat(ts_2)
return ts_2_dt - ts_1_dt
ts_1 = "2022-10-29T16:30:00+05:30"
ts_2 = "2022-10-29T17:30:00+05:30"
delta: datetime.datetime = duration_between(ts_1, ts_2)
print(delta) # 1:00:00
print(delta.total_seconds()) # 3600.0
To obtain the delta in other common formats (years, days, hours, minutes, seconds, microseconds), see this answer: https://stackoverflow.com/a/47207182/11597788

"PT" Formatted time string in python

I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.
I'd like to turn that string into an int which presents the amount of seconds in total.
I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.
String example:
x="PT4M13S"
there is a third-party library that can parse these strings, isodate:
import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0
And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():
from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253
What you are trying to do can easily be solved using regex. Try this out:
import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)
Output:
253

Taking time as input in Python

I mean hour and minutes. Taking them as arguments to input() function and assigning it to a variable. Is it possible?
Like this way:
time = input(current time)
In case you need hour and minutes separately
from datetime import datetime
a=datetime.now()
print(a.hour,a.minute)
intput only returns objects of type str (string).
However, you can be inventive by specifying a certain format and performing the conversion using datetime from the standard library:
from datetime import time
time = input('Enter a time in the format HH:MM \n')
# input 15:25
h, m = map(int, time.split(':'))
res = time(hour=h, minute=m)
print(res)
15:25:00

Set precision for milliseconds in datetime string: Python

I have a datetime string "2017-02-14T18:21:14.080+05:30".
The code I used is
from dateutil.parser import parse
print parse("2017-02-14T18:21:14.080+05:30")
The datetime.datetime object I get is
2017-02-14 18:21:14.080000+05:30
Is there anyway python allows me to set the precision of the milliseconds value displayed before timezone info to 3 in order to get the output as
2017-02-14 18:21:14.080+05:30
There is no built-in way to ask Python to display dates with milliseconds.
You'll have to do a bit of string manipulation to get the desired result:
from dateutil.parser import parse
import datetime as DT
date = parse("2017-02-14T18:21:14.080+05:30")
microsecond = date.microsecond
millisecond = int(round(microsecond/1000))
print(str(date).replace('.{:06d}'.format(microsecond),
'.{:03d}'.format(millisecond)))
yields
2017-02-14 18:21:14.080+05:30
See this post for solutions and
discussion of how to convert microseconds to milliseconds. Note that one of the
difficulties is that date.microsecond may return a number with fewer than 6
digits, and if microseconds are 0, on some OSes, str(date) may drop the
microseconds altogether). This
is why some pains were taken above to format microseconds to 6 digits before
replacing with milliseconds formatted to 3 digits.
Using the code above, on an OS which drops microseconds when zero, no
milliseconds would be shown. If you wish to always show milliseconds formatted
to 3 decimal places, you'll have to build the date string from scratch:
from dateutil.parser import parse
import datetime as DT
date = parse("2017-02-14T18:21:14.080+05:30")
microsecond = date.microsecond
millisecond = round(microsecond/1000)
utcoffset = date.strftime('%z')
utcoffset_string = '{}:{}'.format(utcoffset[:-2], utcoffset[-2:])
print('{}{}{}'.format(date.strftime('%Y-%m-%dT%H:%M:%S'),
'.{:03d}'.format(millisecond),
utcoffset_string))

How to convert time into seconds python?

Hello I am using the daytime module in python 3.3 to takeaway two times like this:
time_format = '%H:%M:%S'
total_time = datetime.strptime(time_left_system, time_format) - datetime.strptime(time_entered_system, time_format)
how would i convert this into seconds so i could print it like this?: 60 mph
Thanks
You are going to want to use the timedelta type from the datetime module, timedelta.total_seconds() will give you the time elapsed in seconds. you already have a timedelta by subtracting one datetime from the other, so you are set for the next step.From there I don't know how you are converting it to mph, probably you are measuring against a fixed distance, just like people on the race track calculate with chronometers given the seconds a car took in a set track distance, but since you don't give the info on how you convert it I can't help you on that part.

Categories

Resources