This should be easy, but as ever Python's wildly overcomplicated datetime mess is making simple things complicated...
So I've got a time string in HH:MM format (eg. '09:30'), which I'd like to turn into a datetime with today's date. Unfortunately the default date is Jan 1 1900:
>>> datetime.datetime.strptime(time_str, "%H:%M")
datetime.datetime(1900, 1, 1, 9, 50)
datetime.combine looks like it's meant exactly for this, but I'll be darned if I can figure out how to get the time parsed so it'll accept it:
now = datetime.datetime.now()
>>> datetime.datetime.combine(now, time.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(now, datetime.datetime.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not datetime.datetime
>>> datetime.datetime.combine(now, datetime.time.strptime('09:30', '%H:%M'))
AttributeError: type object 'datetime.time' has no attribute 'strptime'
This monstrosity works...
>>> datetime.datetime.combine(now,
datetime.time(*(time.strptime('09:30', '%H:%M')[3:6])))
datetime.datetime(2014, 9, 23, 9, 30)
...but there must be a better way to do that...!?
Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.
Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.
The function signature says:
datetime.combine(date, time)
so pass a datetime.date
object as the first argument, and a datetime.time
object as the second argument:
>>> import datetime as dt
>>> today = dt.date.today()
>>> time = dt.datetime.strptime('09:30', '%H:%M').time()
>>> dt.datetime.combine(today, time)
datetime.datetime(2014, 9, 23, 9, 30)
pip install python-dateutil
>>> from dateutil import parser as dt_parser
>>> dt_parser.parse('07:20')
datetime.datetime(2016, 11, 25, 7, 20)
https://dateutil.readthedocs.io/en/stable/parser.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With