converting json date format from string to datetime format in python
Question:
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
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??
Answers:
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.
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
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??
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.