Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse time string without date and date string without time?

Is there any way to automatically parse strings with time only to datetime.time object (or something similar)? Same for datetime.date.

I've tried dateutil, arrow, moment, pandas.to_datetime. All these parsers create timestamps with a current date.

>>> from dateutil.parser import parse
>>> parse('23:53')
datetime.datetime(2019, 1, 8, 23, 53)  # datetime.time(23, 53) expected
>>> parse('2018-01-04')
datetime.datetime(2018, 1, 4, 0, 0)  # datetime.date(2018, 1, 4) expected

UPD:

Thanks for the responses. Think that I should clarify the problem.

The program doesn't know what will be in the input (timestamp, date or time), and it should decide to set appropriate type. The problem is to distinguish these types.

For example, I can parse 23:53 and get a timestamp. How can I decide to extract the time from it or not?

like image 666
felytic Avatar asked Sep 09 '26 02:09

felytic


1 Answers

You can use fromisoformat() from datetime.

import datetime
datetime.time.fromisoformat('23:53')
datetime.date.fromisoformat('2018-01-04')
like image 95
Shaac Avatar answered Sep 10 '26 15:09

Shaac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!