开发者

Find previous calendar day in python [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How can I subtract a day from a python date?

I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text fi开发者_如何学JAVAle for some processing. How do I find the previous day's date in python?


Here you go:

>>> print datetime.date.today()-datetime.timedelta(1)
>>> 2010-06-19


Say you start with a string '2010_05_1'. Then the similar string for the previous day is:

>>> import datetime
>>> s = '2010_05_1'
>>> theday = datetime.date(*map(int, s.split('_')))
>>> prevday = theday - datetime.timedelta(days=1)
>>> prevday.strftime('%Y_%m_%d')
'2010_04_30'
>>> 

Of course you'll encapsulate all of this into one handy function!


You can use the datetime module.

import datetime
print (datetime.date(year, month, day) - datetime.timedelta(1)).isoformat()


In short:

  1. Convert the year/month/day to a number.
  2. Subtract 1 from that number.
  3. Convert the number to year/month/day.

You will find the localtime and mktime functions from the time module helpful.

(Also, since the time module deals with seconds, you would subtract 86400 instead of 1.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜