I have a situation where I need to find the previous date from the date_entry where the date_entry is string, I managed to do this:
>>> from datetime import timedelta, datetime
>>> from time import strptime, mktime
>>> date_str = '20130723'
>>> date_ = strptime(date_str, '%Y%m%d')
>>> date_
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=204,tm_isdst=-1)
>>> datetime.fromtimestamp(mktime(date_))-timedelta(days=1)
datetime.datetime(2013, 7, 22, 0, 0)
>>>
But, for this I have to import the modules timedelta, datetime, strptime and mktime. I think this really an overkill to solve this simple problem.
Is there any more elegant way to solve this (using Python 2.7) ?
Just use datetime.datetime.strptime class method:
>>> import datetime
>>> date_str = '20130723'
>>> datetime.datetime.strptime(date_str, '%Y%m%d') - datetime.timedelta(days=1)
datetime.datetime(2013, 7, 22, 0, 0)
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