3

How would I exactly go about offsetting the timestamp returned by datetime.utcnow() by any amount of time such as a day?

For example:

now = datetime.utcnow().isoformat() + 'Z'

I need the above offset by a day. Having a minor issue when my script crosses into the daylight savings time conversion but I dont need to see past it however since it loads today also it dies because the python script errors doing work on the date today now.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
TULOA
  • 147
  • 1
  • 10

1 Answers1

4

To simply add a certain delta time onto UTC add a timedelta:

from datetime import datetime, timedelta

now = (datetime.utcnow() + timedelta(days=3)).isoformat() + 'Z'

print(now)

Output:

2018-11-06T16:55:06.535804Z

More info on python with timezones can be found at Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

With 3.7 datetime.strptime and datetime.strftime even recognize 01:30 as %z - up to 3.6 the colon would make it crash :)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thanks much. I couldnt figure out how to pair the two. That works perfectly. – TULOA Nov 03 '18 at 17:43
  • 1
    Don't use utcnow() since it produces different values depending on the TZ of your system. Use datetime.datetime.now(tz=timezone.utc) instead. – ruralcoder Feb 28 '20 at 18:42