Home > Blockchain >  Datetime creation in Python for humans
Datetime creation in Python for humans

Time:07-16

Could you please recommend a Python library which can creates datetime from strings like these?

Sunday, 17 July 2022 - 01:00 UTC

7/14/2022 4:37:11 PM

And from any other typical human-readable forms. Without additional conversion from my side. Something like that:

dt = cool_dt_lib.create('Sunday, 17 July 2022 - 01:00 UTC')

CodePudding user response:

If you already know all the date format you'll encounter, you can store them in a list and loop over it.

from datetime import datetime

FORMATS = ["%A, %d %B %Y - %H:%M %Z", "%m/%d/%Y %I:%M:%S %p"]

def try_formats(date_str: str) -> datetime:
    for d_format in FORMATS:
        try:
            datatime_obj = datetime.strptime(date_str, d_format)
            return datatime_obj
        except ValueError:
            pass
        
    raise ValueError(f"No valid format for {date_str}")
    
str_dates = [
    "Sunday, 17 July 2022 - 01:00 UTC",
    "7/14/2022 4:37:11 PM"
]

[try_formats(d) for d in str_dates]
# [datetime.datetime(2022, 7, 17, 1, 0),
#  datetime.datetime(2022, 7, 14, 16, 37, 11)]

If you don't know which format you'll encounter, performance doesn't matter, and you want to save some line of codes, you can use python-dateutil.

from dateutil import parser

[parser.parse(d) for d in str_dates]
# [datetime.datetime(2022, 7, 17, 1, 0, tzinfo=tzutc()),
#  datetime.datetime(2022, 7, 14, 16, 37, 11)]
  • Related