-1

I'm using Python and I need to get the time in a certain format that this API uses. So I need to get current time in the format of yyyy-mm-ddThh:mm:ss.000Z and then also create a new date in the future by adding a number of days to it.

So if I could get the current time of 2017-08-19T07:00:00.000Z and add 30 days to it to get 2017-09-18T07:00:00.000Z. What would be the easiest way to write this in Python?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jason Murray
  • 147
  • 2
  • 4
  • 13

1 Answers1

12

Current date

import datetime
now = datetime.datetime.now()
format_iso_now = now.isoformat()

Add 10 days

from datetime import timedelta
later = now + timedelta(days=10)
format_later_iso = later.isoformat()

Output

print(format_iso_now, format_later_iso)

2017-08-20T02:43:07.177167 2017-08-30T02:43:07.177167

And to match your needs

print(now.strftime('%Y-%m-%d %H:%M:%S:%fZ'))

2017-08-20 02:48:00:103856Z

More details on documentation

Cătălin Florescu
  • 5,012
  • 1
  • 25
  • 36
  • Awesome thanks!! What if I needed the current time to be in UTC of my current time zone in US CST and account for daylight savings time? Right now it would be UTC = now + timedelta(hours=5) but later in the year it would be UTC = now + timedelta(hours=6) – Jason Murray Aug 20 '17 at 00:09
  • @JasonMurray i don't understand your question. Can you explain? – Cătălin Florescu Aug 20 '17 at 00:11
  • Oh i think i found the answer i would use utcnow instead of now – Jason Murray Aug 20 '17 at 00:22