Python convert date string to python date and subtract

python

Solution

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)

Problem

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) ?

Original source