Home > Mobile >  How to custom format date in Python?
How to custom format date in Python?

Time:03-08

I have this format in my input program: "2022-03-07T09:31:49.06251Z" and I need change to "YYYYMMDD HH:MM:SS"

Note, the timezone is the same.

sample:

2022-01-26T14:57:33.2400054Z => 20220126 14:57:33

I find any code whith date.fromisoformat and/or .isoformat() but is not custom format.

EDIT:

I try this: datetime.strptime("2022-03-08T09:57:43.7227461Z", "%Y-%m-%dT%H:%M:%S.%fZ") but I have this error:

[ERROR] ValueError: time data '2022-03-08T09:57:43.7227461Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

CodePudding user response:

You can use a library called dateutil.

from dateutil import parser
parsed_date = parser.parse('2022-03-07T09:31:49.06251Z')
print(parsed_date)
>>> datetime.datetime(2022, 3, 7, 9, 31, 49, 62510, tzinfo=tzutc())
print(parsed_date.strftime("%Y%m%d %H:%M:%S")
>>> '20220307 09:31:49'
  • Related