How can I know if a date is prior to today?
Tim Chase
python.list at tim.thechases.com
Wed Mar 25 09:51:42 EDT 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)
> else:
> print time.strftime("%b%d", mytime)
Well, date/datetime objects are directly comparable:
import datetime
today_day = datetime.date.today()
other = datetime.datetime.fromtimestamp(your_timestamp)
if other.date() == today_day:
fmt = "%H:%M"
else:
fmt = "%b%d"
print other.strftime(fmt)
-tkc
More information about the Python-list
mailing list