Convert datetime UTC format and then calculate timedelta

Question:

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'

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:UsersuserDesktopPYTHONtiny3.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.

Asked By: PythonNoob

||

Answers:

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.

Answered By: gtj520
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.