I'm parsing date time from string in Python. I like the fact that in pandas, I can define 1 single format, but pandas still allows me to be flexible in my input. As follows
>>> format = '%Y%m%d %H:%M:%S.%f'
>>> pd.to_datetime('20200106 23:00', format=format)
Timestamp('2020-01-06 23:00:00') ## OK
>>> pd.to_datetime('20200106 23:00:00', format=format)
Timestamp('2020-01-06 23:00:00') ## OK
>>> pd.to_datetime('20200106 23:00:00.000', format=format)
Timestamp('2020-01-06 23:00:00') ## still ok
With Pandas, I can accept user input that looks like %H:%M or %H:%M:%S, or %H:%M:S.%f. As long as it doesn't violate the original format, it's fine. I like this flexibility.
Does that same behavior exist in datetime?
>>> datetime.strptime('20200106 23:00:00.000000', format)
datetime.datetime(2020, 1, 6, 23, 0) ## OK
>>> datetime.strptime('20200106 23:00:00', format) ## NOT OK
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '20200106 23:00:00' does not match format '%Y%m%d %H:%M:%S.%f'
strptime doesn't like it. What am I supposed to do? List all formats that user might put in? And do a bunch of tries?
datetime. Use a third-party library such aspython-dateutilorpendulum.