Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting json date format from string to datetime format in python

currently im trying to convert an incoming JSON data with a time stamp in string format to a datetime in python.

the following data of the string is this:

2022-12-30T16:27:56.9871548+08:00

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to convert this string to datetime using strptime and when i tried doing this below:

from datetime import datetime
date = datetime.strptime('2022-12-30T16:27:56.9871548+08:00', '%y-%M-%dT%H:%m:%S.%f%z')

the error gave me this

ValueError: time data '2022-12-30T16:27:56.9871548+08:00' does not match format '%y-%M-%dT%H:%m:%S.%f%z'

how can i fix this??

>Solution :

The format code used has a number of errors. Corrected would be %Y-%m-%dT%H:%M:%S.%f%z (year/month/minute were wrong case) but note that %f only supports microseconds (6 digits after the decimal) and your example has 7.

This format has a special function in datetime that supports it called .fromisoformat(), but before Python 3.11 it only supported 6 digits as well. Here’s a workaround:

#!python3.10
import datetime as dt
import re

s = '2022-12-30T16:27:56.9871548+08:00'
# replace more than 6 digits in a row with exactly the first 6 digits.
print(dt.datetime.fromisoformat(re.sub(r'(\d{6})\d+', r'\1', s)))
# 2022-12-30 16:27:56.987154+08:00

As of Python 3.11:

#!python3.11
import datetime as dt
import re

s = '2022-12-30T16:27:56.9871548+08:00'
print(dt.datetime.fromisoformat(s))
# 2022-12-30 16:27:56.987154+08:00

Note that in both cases precision is lost and only microseconds are retained.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading