2009-05-28

 

Python: what day is tomorrow?

Easy yes? Well - sort of. It's easy if you want to know tomorrows date. It's not so easy if you want to work out the next date from "any" other date.

This is by no means perfect - it's work in progress, but for now it works for me:

The simple solution to calculate tomorrow (from the Python Cookbook):

import datetime
today = datetime.date.today( )
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
print yesterday, today, tomorrow


The harder one - calculating tomorrow from any other date:

import datetime
import re
somedate = "2007-02-28"
sd_elements = re.split( "-", str( somedate ) )
d = datetime.datetime( int( sd_elements[0] ), int( sd_elements[1] ), int( sd_elements[2] ) )
tomorrow = d + datetime.timedelta(days=1)
m = re.search( '(\d\d\d\d-\d\d-\d\d)', str( tomorrow ), re.IGNORECASE )
tomorrow = str( m.group(1) )
print "If today is " + str( somedate ) + " then tomorrow must be " +str( tomorrow )


Like I said - most likely not perfect.

Labels:


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?