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))
Related
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
I need to specify a parameter to a python script indicating time back from now. For example 1d is 1 day from now, 2h is 2 hours from now, 2d3h is 2 days, 3 hours from now. Similar to the journalctl --vacuum-time format (reference).
For example, this script will collect the data between now and 2 days and 3 hours in the past:
collect_data_script.py --start=2d3h
Is there some standard way to handle this parameter and a package that can process this time format? Or I will have to write it from scratch?
The ISO 8601 duration format like 2DT3H for "2 days (time designator) 3 hours" can be parsed using module isodate from Gerhard Weiss:
implements ISO 8601 date, time and duration parsing. The implementation follows ISO8601:2004 standard
parse_duration:
parses an ISO 8601 duration string into a timedelta or Duration object.
Example:
import isodate
isodate.parse_duration('p2d3h'.upper()) # prefix with 'p' for period and to uppercase
# will raise ValueError because ISO 8601 time designator 'T' missing
timedelta = isodate.parse_duration('p2dt3h'.upper()) # insert 'T' to work
# datetime.timedelta(2, 10800)
print(timedelta)
# 2 days, 3:00:00
Similar modules
arrow: offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps.
duration: python time duration conversion module
iso8601: Simple module to parse ISO 8601 dates
See also:
How can I parse and compare ISO 8601 durations in Python?
#hc_dev solution will work. However, I used a slightly different one that needed fewer additional modules. Just posting here for reference:
from datetime import datetime, timedelta
from dateutil import parser
def process_cmd_time(time_str, bound) -> datetime:
"""
Convert passed string to the datetime object.
Will throw ParseError or ValueError if the string is invalid
Keyword arguments:
time_str - string representation of the time to set
bound - flag to force time bound to 24h from now
"""
time_str = time_str.strip()
go_back = time_str[0] == '-'
# Attempt to get the date. Will throw ParseError if invalid
input_date = parser.parse(time_str)
# If the time needs to go back, find the delta from the beginning of today,
# then subtract from now
if go_back:
delta_today = input_date - parser.parse("0h0m0s")
input_date = datetime.now() - delta_today
if bound:
delta_time = datetime.now() - input_date
if delta_time.days > 0:
input_date = datetime.now() - timedelta(hours=24, minutes=0, seconds=0)
return input_date
What is this date format 2020-01-13T09:25:19-0330 ? and how can I get the current datetime in this format in python ?
Edited: Also note there are only 4 digits after last -. The API which I need to hit accepts exactly this format.
2nd Edit: Confirmed from api's dev team, last 4 digits are milliseconds, with 0 prepended. ex, 330 is the milliseconds, and they mention it as 0330.
It's an ISO 8601 timestamp format.
In order to get the current time in that format:
from datetime import datetime
print(datetime.now().isoformat())
In your case, the iso format is truncated to seconds, and has a timezone:
from datetime import datetime, timezone, timedelta
tz = timezone(timedelta(hours=-3.5))
current_time = datetime.now(tz)
print(current_time.isoformat(timespec="seconds"))
Where -3.5 is the UTC offset.
If you wish to use the system's local timezone, you can do so like this:
from datetime import datetime, timezone, timedelta
current_time = datetime.now().astimezone()
print(current_time.isoformat(timespec="seconds"))
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
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.