How can I know if a date is prior to today?
python.list at tim.thechases.com
Wed Mar 25 14:51:42 CET 2009
> I have a date expressed in seconds.
> I'd want to pretty print it as "%H:%M" if the time refers to today and
> "%b%d" (month, day) if it's of yesterday or before.
> I managed to do that with the code below but I don't like it too much.
> Is there a better way to do that?
> Thanks in advance.
> import time
> today_day = time.strftime("%d", time.localtime(time.time()))
> mytime = time.localtime(time.time() - (60*60*30)) # dummy time prior
> to today
> if time.strftime("%d", mytime) == today_day:
> print time.strftime("%H:%M", mytime)
> print time.strftime("%b%d", mytime)
Well, date/datetime objects are directly comparable:
today_day = datetime.date.today()
other = datetime.datetime.fromtimestamp(your_timestamp)
if other.date() == today_day:
fmt = "%H:%M"
fmt = "%b%d"
More information about the Python-list