"PT" Formatted time string in python - 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

Related

Convert string to timestamp python

I'm trying to convert the list of str to the list of timestamps, then want to create the list of time delta of timestamps using total_seconds()
from datetime import datetime
a = ['091122333','092222222','093333333']
for i in a:
datetime.strptime(str(i),'%H:%M:%S.%f')
print(a)
It shows the error code of time data '091122333' does not match format '%H:%M:%S.%f'
I want to make timestamp 09(%H)11(%M)22(%S)333(%F) if possible.
Could you give me the advice above?
Thank you very much...
You have to first change the representation ( You have : which is not present in list of string in a) and how You manage what is returned from datetime.strptime (You have to store the value while You iterate through list) like that:
from datetime import datetime
a = ['091122333','092222222','093333333']
for t in range(len(a)):
a[t] = datetime.strptime(a[t],'%H%M%S%f')
delta = a[1]-a[0]
print(delta.total_seconds())
The format passed to strptime should represent the format used in the string (there are no colons in your string):
from datetime import datetime
a = ['091122333', '092222222', '093333333']
for i in a:
dt = datetime.strptime(str(i), '%H%M%S%f')
print(dt)
Out:
1900-01-01 09:11:22.333000
1900-01-01 09:22:22.222000
1900-01-01 09:33:33.333000

How to get timedelta in seconds from a string? Example: +414 00:45:41.004000

I have data of timedeltas which looks like this:
time_delta = '+414 00:45:41.004000'
So, these values are strings and they are of the format ddd hh:mm:ss.f. I now want to get this deltas to seconds. I tried to use .total_seconds() but it did not work.
How could I achieve what I am trying to do?
If you always assume the same input format, you can build a function as below (result to be checked with a simple case) :
import datetime as dt
def parseTimeDelta(time_delta_str):
splitted = time_delta_str.split(' ')
day_part = int(splitted[0][1:])
time_part = dt.datetime.strptime(splitted[1], "%H:%M:%S.%f")
delta = dt.timedelta(days=day_part, hours=time_part.hour, minutes=time_part.minute, seconds=time_part.second,microseconds=time_part.microsecond)
return delta.total_seconds()
time_delta = '+414 00:45:41.004000'
parseTimeDelta(time_delta)
can do this with pandas library
import pandas as pd
# Create the Timedelta object
td = pd.Timedelta('3 days 06:05:01.000000111')
print(td)
print(td.seconds)
Unfortunately we can't create a timedelta with a formatted string directly, but we can get a similar effect with regex then unpack parsed values into a timedelta.
import re
import datetime
# Create parser for your time format with named groups that match timedelta kwargs
time_parser = re.compile(r"\+(?P<days>\d+)\s+(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})\.(?P<microseconds>\d+)")
# Get the values from your example string
regex_match = time_parser.match("+414 00:45:41.004000")
time_dict = regex_match.groupdict()
# Convert the time values to integers from strings
timedelta_kwargs = {k: int(v) for k, v in time_dict.items()}
# Make a time delta object
delta = datetime.timedelta(**timedelta_kwargs)
# Get total seconds
delta_in_seconds = delta.total_seconds()
Organise that into some functions and you'll get the functionality you're looking for with standard python packages.

converting a list of string with the format 68.830320 in 'time' format without date information. The time format is second.millisecond

I have a string in the form of 68.830320 Format. this I need to convert to time Format in second.millisecond. it does not contain date or any other values. I cannot use strptime since the Format is not right. tstamp that I'm trying to parse is a list of calues containg values with decimal Point. I cannot round this value. it still gives error. I'm not sure how to proceeed. please help!
tried a lot of threads from here that always take the datetime object. But since my Format is not in the same way, I cannot use that info. I have tries .time dateutil, and everything else available. I still cannot solve this problem
tstamp = child2.get('timestamp').replace(" ", "").replace("\n", "")
print(tstamp)
parser.parser(tstamp)
format_time = datetime.date(tstamp)
print(format_time)
A number of seconds isn't a datetime, it's a timedelta. It isn't a datetime because you can't take the string "68.830320" and set the hands on a wall clock to represent that time.
Convert your string to a timedelta like this:
>>> from datetime import timedelta
>>> mytime = timedelta(seconds=float("68.830320"))
>>> mytime
datetime.timedelta(0, 68, 830320)
You can then add the timedelta to a datetime to get a wall clock time.

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))

datetime - how to add seconds to Epoch?

I do not even know how to tackle this. I need to first turn a str() into a datetime object, convert it to epoch time add a number of seconds then turn it back into the date in a properly formatted object. A sample of the str is:
"2016-11-04T03:02:00Z"
I'm guessing some regex to break up the str()??
Use a timedelta object, e.g:
from datetime import datetime, timedelta
TIMESTRING_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
dt = datetime.strptime('2016-11-04T03:02:00Z', TIMESTRING_FORMAT)
ndt = dt + timedelta(seconds=5)
print datetime.strftime(ndt, TIMESTRING_FORMAT)
See docs https://docs.python.org/2/library/datetime.html and make sure that my TIMESTRING_FORMAT string is correct.

Categories

Resources