简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM