How can I know if a date is prior to today?

Giampaolo Rodola' gnewsg at gmail.com
Wed Mar 25 10:20:54 EDT 2009


On 25 Mar, 14:51, Tim Chase <python.l... at tim.thechases.com> wrote:
> > 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

Thanks, it did the job.

--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil



More information about the Python-list mailing list