Prasanna K
Prasanna K

Reputation: 27

want to convert json timestamp into normal timestamp (CST Hrs) in python

I am downloading a json file containing timestamp using python . But the timestamp i am getting is below format

 `2021-04-01T21:43:52.757Z`

Want to convert into normal timestamp (CST Hrs). I also see that the time is increased by 4 hours when i compare the report manually.

 `4/1/2021  5:43:53 PM`

The above hours is 4 hrs less when i compare with json file entry. Please advise me.

Upvotes: 0

Views: 243

Answers (1)

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

You need to use python's datetime module to handle this. The Z in the string actually means time zone 0 or UTC time which is 6 hours ahead of CST not 4:

import datetime

date_object = datetime.datetime.strptime(
    "2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)

date_object = date_object - datetime.timedelta(hours=6)

print(
    f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)

Which will give this output:

4/1/2021 03:43:52 PM

have to use an f string if you want non zero padded dates because its not available in datetime according to the docs

You can use pytz module to deal with time zones directly and not hardcode them if you want. Or if you are on python 3.9 you can use timezone objects to create timezones yourself

Upvotes: 1

Related Questions