1

I'm reading in some info from an API and the time is being displayed as:

2021-01-29T13:29:19.668Z

However, I would like this to read as:

Jan 29, 2021 @ 1:29pm

Is there a way to do this with a library? Or will I have to create something myself.

baduker
  • 19,152
  • 9
  • 33
  • 56
Kevin Lay
  • 17
  • 6
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Feb 08 '21 at 06:33
  • Btw. the title is misleading; you do not convert the time to another zone (13:29 == 1:29 PM). – FObersteiner Feb 08 '21 at 08:25

3 Answers3

2
from datetime import datetime

string_time = "2021-01-29T13:29:19.668Z"

# see https://strftime.org/ for definitions of strftime directives
dt_format = "%Y-%m-%dT%H:%M:%S.%fZ"

output_format = "%b %d, %Y @ %-I:%-M%p" # the %p is uppercase AM or PM

output = datetime.strftime(datetime.strptime(string_time, dt_format), output_format)

# lower case the last 2 characters of output
# and join with all characters except the last 2
print(''.join((output[:-2], output[-2:].lower())))

OUTPUT: Jan 29, 2021 @ 1:29pm

dmmfll
  • 2,666
  • 2
  • 35
  • 41
1

You might want to explore pendulum. pendulum is Python's datetime made easy!

Just install it with:

$ pip install pendulum

Usage for your case:

import pendulum

dt = pendulum.parse("2021-01-29T13:29:19.668Z")
print(dt.format("MMM DD, YYYY @ h:mm A"))

Output:

Jan 29, 2021 @ 1:29 PM

EDIT: To get the time in EST (modifying the time), just do this:

import pendulum

dt = pendulum.parse("2021-01-29T13:29:19.668Z")
print(dt.in_tz("America/Toronto").format("MMM DD, YYYY @ h:mm A"))

Output:

Jan 29, 2021 @ 8:29 AM

However, if you don't want to modify the output but just set the timezone, try this:

dt = pendulum.parse("2021-01-29T13:29:19.668Z").set(tz="America/Toronto")
print(dt.timezone)
print(dt)
print(dt.format("MMM DD, YYYY @ h:mm A"))

Output:

Timezone('America/Toronto')
2021-01-29T13:29:19.668000-05:00
Jan 29, 2021 @ 1:29 PM
baduker
  • 19,152
  • 9
  • 33
  • 56
  • This is perfect. One more slight twist. If this is GMT 0 time. How would I change it to EST time ? (-5 hours) – Kevin Lay Feb 07 '21 at 20:57
  • I was able to do this using: dt = dt.subtract(hours=5) – Kevin Lay Feb 07 '21 at 21:18
  • 1
    one small other thing. 3:00PM was showing as 3:PM I fixed this by : From: `print(dt.format("MMM DD, YYYY @ h:m A"))` to: `print(dt.format("MMM DD, YYYY @ h:mm A"))` – Kevin Lay Feb 07 '21 at 21:22
-1

I used the datetime module. And used the split function to separate the date from the time and the rest as well

import datetime

DT = "2021-01-29T13:29:19.668Z"

date,time = DT.split("T")

Year, Month, Day = date.split("-")

Hour, Minute, Seconds = time.split(":")

x = datetime.datetime( int(Year), int(Month), int(Day), int(Hour), int(Minute) )

x = x.strftime("%b %d, %Y @ %I:%M %p")

output = ''.join(( x[:-2], x[-2:].lower() ))

print(output)