Find time until a date in Python - 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 comment 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))

Related

How to caculate time diffs between two date times?

diff = reference_time - topic_time
hour = round((reference_time-topic_time) / datetime.timedelta(hours=1))
if reference_time = '2020-08-23 07:00:10' and topic_time = '2020-08-22 00:00:00', the 'diff' variable is:
days = 1
seconds = 25210
The 'hour' conversion code make the hour = 31, which seems incorrect. The max diff should be less than 24 hours in one day. How to calculate time diffs and convert to hours in this case?
import datetime
firstTime = datetime.datetime.utcnow()
secondTime = datetime.datetime.utcnow() + datetime.timedelta(hours=5)
diff = secondTime - firstTime
hours = diff.total_seconds() // 3600
print(hours) # Answer is 5
reference_time = datetime.datetime(2020,8,23,7)
topic_time = datetime.datetime(2020,8,22,0)
hours = (reference_time - topic_time).total_seconds() // 3600
days = hours // 24
hours = hours - (days*24)
print('days: %d, hours: %d' % (days, hours) ) # days:1, hours:7

How to convert a date to a number of days from 0001-01-01?

How can I convert any date to just number of days? This is what I tried:
import datetime
import calendar
def leap_day_counter(yr):
leap_days = 0
# since 1582 11 days are missing
if yr >= 1582:
leap_days += 11
for specific_year in range(1, yr):
if calendar.isleap(specific_year):
leap_days += 1
return leap_days
def month_to_day(yr, mth):
all_days = 0
for specific_month in range(1, mth+1):
days_in_month = calendar.monthrange(yr, specific_month)
all_days += days_in_month[1]
return all_days
date = datetime.datetime.now()
days_passed = ((date.year * 365) + leap_day_counter(date.year)) + month_to_day(date.year, date.month) + date.day
print(days_passed)
I got 737 158 days but according to https://www.timeanddate.com/date/durationresult.html I should have 736 755 days. Do I miss something? Is there easier way to do this?
This helps
from datetime import date
d0 = date(2000, 1, 01)
d1 = date.today()
delta = d1 - d0
print delta.days
Are the amount of days in a year correct for you?
01/01/0001 - 01/01/2018 has 736,696, you say there is 737,060. This is roughly 1 year too many.
(date.year - 1) * 365
After fixing the above, we should check if 01/01/0001 - 01/02/2018 works.
The website says 736,727, where you say 736,754. Which is about the entire month of February too many.
for specific_month in range(1, mth)
You have one too many leap years.
for specific_year in range(1, yr)
You can also simplify this code to:
def leap_day_counter(y):
y -= 1
return y//4 - y//100 + y//400
This is now the same as datetime.datetime.now().toordinal().
The number of days between two dates can be calculated as below: For more see here. Hope this may help
>>>enddate = "2018/03/12" +" 23:59"
>>>enddate = datetime.strptime(enddate, "%Y/%m/%d %H:%M")
>>>(enddate-datetime.now()).days
12
Update:edit
>>>import datetime
>>>checkdate = datetime.datetime.strptime("0001-01-01", "%Y-%m-%d")
>>>days = (datetime.datetime.now()-checkdate).days
>>>days
736757
2 days difference because start days and end date are excluded.

Python timedelta in full days, full hours and so on

I want some how to print a message like:
"Since then, x days, y hours, z minutes and w seconds have elapsed".
Currently I'm doing something like this but I miss the remainders plus (most importantly) I don't like it. There should be something more beautiful
dt = (datetime.now() - datetime(year=1980, month=1, day=1, hour=18)).total_seconds()
full_days = int(dt // (3600 * 24))
full_hours = int((dt - full_days * (24 * 3600)) // 3600)
full_minutes = int((dt - full_days * (24 * 3600) - full_hours * 3600) // 60)
residual_seconds = dt - full_days * (24 * 3600) - full_hours * 3600 - full_minutes * 60
print(full_days, full_hours, full_minutes, residual_seconds)
You can use timedelta:
from datetime import datetime
fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))
Output:
Since then, 13266 days, 23 hours, 5 minutes and 55 seconds have elapsed
Try this, I hope this will be useful for you:
import datetime
from dateutil.relativedelta import relativedelta
end = '2016-01-01 12:00:00'
begin = '2015-03-01 01:00:00'
start = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(begin, '%Y-%m-%d %H:%M:%S')
diff = relativedelta(start, ends)
print "%d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
Output:
0 year 10 month 0 days 11 hours 0 minutes
There is Humanize to convert all sorts of data into human readable formats.
>>> import humanize
>>> from datetime import datetime, timedelta
>>> humanize.naturaltime(datetime.now() - timedelta(seconds=3600))
'an hour ago'
This may be deemed more beautiful, but I'm not sure it's actually pythonic. Personally I'd just hide away the "ugly" code in a function. Anyway,
dt=datetime(2016,1,2,11,30,50)-datetime(2016,1,1)
s=dt.total_seconds()
t=[]
for x in (24*3600,3600,60,1):
t.append(s//x)
s -= t[-1]*x
days,hours,mins,secs=t
>>> print(t)
[1.0, 11.0, 30.0, 50.0]

Python and check if current datetime is in specific range

I am trying to do something similar to this, but i want to specify the start date and end date by actual weekday names and times. For example, I want to check if the current datetime (datetime.datetime.now()) is in between Tuesday at 4:30pm and Thursday at 11:45am. This would update weekly so it has to be by Tuesday/Thursday mentality.
I have thought about how to do the weekdays (but i don't know how to wrap the time part into it):
TimeNow = datetime.datetime.now()
if TimeNow.weekday() >= 1 and TimeNow.weekday() <= 3:
#runcodehere
Any thoughts on how i would do this?
Neatest way is to use the amount of minutes elapsed in a week:
def mins_in_week(day, hour, minute):
return day * 24 * 60 + hour * 60 + minute
if (mins_in_week(1, 16, 30) <
mins_in_week(TimeNow.weekday(), TimeNow.hour, TimeNow.minute) <
mins_in_week(3, 11, 45)):
....
It's not very neat but something like this should work:
TimeNow = datetime.datetime.now()
if (TimeNow.weekday() == 1 and ((TimeNow.hour() == 4 and TimeNow.minute >= 30) or TimeNow.hour > 4)) or (TimeNow.weekday() == 2) or (TimeNow.weekday() == 3 and (TimeNow.hour() < 11 or (TimeNow.hour() == 11 and TimeNow.minute <= 45)):
#runcodehere
You can use a combination of and and or, and have different conditions for each day:
import datetime
TimeNow = datetime.datetime.now()
day_now = TimeNow.weekday()
time_now = TimeNow.hour*60 + TimeNow.minute
if (day_now == 1 and time_now > 990) or (day_now == 2) or (day_now == 3 and time_now < 705):
# do something

Can't calculate the difference between 2 days in hours [duplicate]

This question already has answers here:
How do I check the difference, in seconds, between two dates?
(7 answers)
Closed 8 years ago.
I need to check if some date and now arent' different more than in 18 hours:
dt = parser.parse("some date 123") #working well
diff = datetime.datetime.now() - dt
print "datetime.datetime.now() - dt = %s" % diff # 31 days, 0:08:04.882498 -- correct
print "datetime.datetime.now() - dt seconds = %s" % diff.seconds # 484 -- too
(datetime.datetime.now() - dt).seconds / 3600) < 18 # returns True always
As you can see, even though the dates are different in 31 days, the amount of seconds if very little which doesn't allow me to calculate the amount of hours. Why is it so small? Should it be x * 60 * 60 * amount_of_days? And how can I do what I want?
seconds is returning just the number of seconds, not the total number of seconds, for that you can use timedelta.total_seconds.
You may try this:
from datetime import date
date0 = date(2014, 9, 07)
date1 = date(2014, 9, 05)
diff = date0 - date1
print diff.days * 24
Also check How do I check the difference, in seconds, between two dates?
or
>>> from datetime import datetime
>>> date0 = datetime(2014,09,07,0,0,0)
>>> date1 = datetime(2014,09,01,23,59,59)
>>> date0-date1
datetime.timedelta(6, 1)
>>> (date0-date1).days * 24
144

Categories