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

G

Giampaolo Rodola'

Hi,
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)


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

Paul McGuire

Hi,
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.

Use datetime module.

import time
from datetime import datetime
now = time.time()
thisTimeYesterday = now - 24*3600

print datetime.fromtimestamp(now) < datetime.today()
print datetime.fromtimestamp(thisTimeYesterday) < datetime.today()


-- Paul
 
T

Tim Chase

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
 
J

John Machin

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

time tuples are directly comparable, too:

import time
today_day = time.localtime(time.time())[:3]
other = time.localtime(your_timestamp)
if other[:3] == today_day:
etc
etc

Cheers,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top