开发者

Find time until a date in Python

What's the best way to find the time until a date. I would like to know the years, months, days and hours.

I was hoping somebody had a nice function. I want to do something like: This com开发者_运维技巧ment was posted 2month and three days ago or this comment was posted 1year 5months ago.


datetime module, datetime and timedelta objects, it will give you days and seconds.

In [5]: datetime.datetime(2009, 10, 19) - datetime.datetime.now()
Out[5]: datetime.timedelta(2, 5274, 16000)

In [6]: td = datetime.datetime(2009, 10, 19) - datetime.datetime.now()

In [7]: td.days
Out[7]: 2

In [8]: td.seconds
Out[8]: 5262


You should use dateutil.relativedelta.

from dateutil.relativedelta import relativedelta
import datetime
today = datetime.date.today()
rd = relativedelta(today, datetime.date(2001,1,1))
print "comment created %(years)d years, %(months)d months, %(days)d days ago" % rd.__dict__


Let's asume you have the future datetime in a variable named eta:

(eta - datetime.datetime.now()).total_seconds()

Datetime difference results in a timedelta object, which happens to implement a method named total_seconds. That's it :)


I was looking for something more like this ... which took some hard work to find.

import datetime

SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
MONTH = 30 * DAY

def get_relative_time(dt):    
    now = datetime.datetime.now()
    delta_time = dt - now

    delta =  delta_time.days * DAY + delta_time.seconds 
    minutes = delta / MINUTE
    hours = delta / HOUR
    days = delta / DAY

    if delta <  0:
        return "already happened"

    if delta < 1 * MINUTE:    
      if delta == 1:
          return  "one second to go"
      else:
          return str(delta) + " seconds to go"


    if delta < 2 * MINUTE:    
        return "a minute ago"


    if delta < 45 * MINUTE:    
        return str(minutes) + " minutes to go"

    if delta < 90 * MINUTE:    
        return "an hour ago"

    if delta < 24 * HOUR:
        return str(hours) + " hours to go"

    if delta < 48 * HOUR:    
        return "yesterday"

    if delta < 30 * DAY:    
        return str(days) + " days to go"


    if delta < 12 * MONTH:    
        months = delta / MONTH
        if months <= 1:
            return "one month to go"
        else:
            return str(months) + " months to go"
    else:    
      years = days / 365.0
      if  years <= 1:
          return "one year to go"
      else:
          return str(years) + " years to go"


may be you want something like this:

import datetime

today   = datetime.date.today()
futdate = datetime.date(2016, 8, 10)

now     = datetime.datetime.now()
mnight  = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (mnight - now).seconds
days    = (futdate - today).days
hms     = str(datetime.timedelta(seconds=seconds))

print ("%d days %s" % (days, hms))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜