Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert datetime UTC format and then calculate timedelta

Been trying to use datetime in UTC/ISO format, which outputs a very finicky format, and then create a time range of 15 min and 1 hour past. Here’s what I have so far:

  1. Was able to successfully format the time according to specifications.

    now = datetime.datetime.utcnow().isoformat()[:-3] + 'Z'

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

Output:

2022-12-16T21:54:12.184Z
<class 'str'>

So far so good. Now, if I try to use it along with timedelta, I get a TypeError:

now = datetime.datetime.utcnow().isoformat()[:-3] + 'Z'
past15min = (now - timedelta(minutes=15))

Output:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\PYTHON\tiny3.py", line 27, in <module>        
    past15min = (now - timedelta(minutes=15))
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

I then tried using the strptime() function, but it complains again because of an unsupported operand.

now_to_datetime = datetime.datetime.strptime(now,"%Y-%m-%dT%H:%M:%S.%fZ")

Output:

past15min = (now - timedelta(minutes=15))
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

Here is the entire script:

now = (datetime.datetime.utcnow().isoformat()[:-3] + 'Z')
now_to_datetime = datetime.datetime.strptime(now,"%Y-%m-%dT%H:%M:%S.%fZ")
past15min = (now_to_datetime - timedelta(minutes=15))
print(past15min)

These attempts, among several others have proven to be a failure. Any help is appreciated.

>Solution :

from datetime import datetime, timedelta

now = datetime.now()
past15min = (now - timedelta(minutes=15)).utcnow().isoformat()[:-3] + 'Z'
print(past15min)

When you use isoformat or strptime, you turn datetime objects into string. As they are turned into string, you can’t use timedelta to calculate time.
So calculate time first before you use methods such as isoformat or strptime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading