John Prawyn
John Prawyn

Reputation: 1663

Python convert date string to python date and subtract

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

Upvotes: 3

Views: 2426

Answers (2)

Aramis NSR
Aramis NSR

Reputation: 1840

Chosen answer is old and works on python 2, returns bellow error for python 3.

Error:

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

Fix + Doing it with PYTHON 3 :

from datetime import datetime,timedelta
date_str = '20130723'
datetime.strptime(date_str, '%Y%m%d') - timedelta(days=1)

Also, use up to date document on Python 3 here: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

Upvotes: 0

falsetru
falsetru

Reputation: 368894

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)

Upvotes: 7

Related Questions