now = datetime.now()
d1 = datetime(now.year, now.month, now.day, now.hour, now.minute, 0)
if now.minute in xrange(46, 60):
res = 0
print now.hour
print now.hour+1
d1 = d1 + timedelta(hours=now.hour+1)
print d1
now.hour prints, for example, 15. Second line shows up 16 but d1 after adding timedelta becomes: 2012-07-21 07:57:00. This date is next day at 7am.
What's wrong?
You create a timedelta with a value of 16 hours and then add that to d1. d1 (if already at 15 hours) plus 16 hours will be 07 hours the next day.
You don't say what you are trying to achieve but if you are trying to increment by one hour then you should use d1 = d1 + timedelta(hours=1);
Related
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 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.
This is part of a bigger problem we're facing but the problem at the moment is splitting time between two datetimes into two rates based on when those hours are in the day. It's quite arbitrary but we treat 7am-7pm as normal hours and the opposite 12 hours as premium.
So for any given pair of datetimes, we need to grade these down so that we know how many normal hours, or how many premium hours there were in that period. A couple of examples:
If we took the next 24 hours, I'd expect an exact split of 12 hours.
> start = datetime.datetime.now()
> end = start + datetime.timedelta(1)
> split_hours(start, end)
(datetime.timedelta(0, 43200), datetime.timedelta(0, 43200))
If we took the next 12 hours, at 20:26, I'd expect 1h26 normal and 10h34m premium rate:
> start = datetime.datetime(2017, 11, 6, 20, 26, 0)
> end = start + datetime.timedelta(hours=12)
> split_hours(start, end)
(datetime.timedelta(0, 5160), datetime.timedelta(0, 38040))
"How do I do that?" is my question. Sorry. I've been thinking through this most of the day but only ever got as far as the following napkin algorithm:
Split range into distinct-date datetime ranges (how?!) and for each:
Count hours before 7am and after 7pm as premium
Count hours between 7am and 7pm
Total them up.
But even there I don't know how to split things up.
There is also a natural extension —that I'll almost certainly have to implement at some point— that also grades weekend hours as premium too. If I could split time (as in my napkin algorithm) it would be easy to tack on but I still don't like how clumsy that "code" is). If your answer covers that too, you can have my firstborn. Well, no, you can have a bounty or something.
I'm doing this in Python without any real library limits (if eg Pandas Just Does™ this) but if you want to submit a raw C or Pseudo code answer, I'm sure I'll be able to read it.
We could:
generate a range of datetime between start and end
loop that range and calculate normal seconds (the length - normal = premium)
Here is the code:
import datetime
def split_hours(start, end):
# Total seconds
length = int((end-start).total_seconds())
# Generator with datetime objects
s = (start + datetime.timedelta(seconds=i) for i in range(length))
# Calculate normal and premium
# normal when hour > 7 AM, smaller than 7 PM and weekday not sat,sun
normal = sum(7 <= i.hour < 19 and i.weekday() not in [5,6] for i in s)
premium = length - normal
d = dict(normal=normal,
premium=premium,
total=dict(h=length/3600,m=length/60,s=length))
return d
And now we can do some tests:
start = datetime.datetime.now()
end1 = start + datetime.timedelta(hours=12)
end2 = start + datetime.timedelta(days=1)
end3 = start + datetime.timedelta(days=24)
print(split_hours(start,end1))
print(split_hours(start,end2))
print(split_hours(start,end3))
Returns:
# 12 hours
{'total': {'h': 12.0, 's': 43200, 'm': 720.0}, 'premium': 26131, 'normal': 17069}
# 1 days / 24 hours
{'total': {'h': 24.0, 's': 86400, 'm': 1440.0}, 'premium': 43200, 'normal': 43200}
# 7 days
{'total': {'h': 168.0, 's': 604800, 'm': 10080.0}, 'premium': 388800, 'normal': 216000}
That would be my approach:
from datetime import datetime, timedelta
def is_premium_time_period(start_time, end_time):
start_time = datetime.strptime(start_time, "%d-%m-%Y %H:%M")
end_time = datetime.strptime(end_time, "%d-%m-%Y %H:%M")
seconds = (end_time - start_time).total_seconds()
minutes = int(seconds / 60)
premium_minutes = 0
regular_minutes = 0
for minute in range(minutes):
premium_start = datetime.strptime("19:00 {}".format(start_time.date()), "%H:%M %Y-%m-%d")
premium_end = premium_start + timedelta(hours=12)
previous_start = premium_start - timedelta(hours=24)
previous_end = previous_start + timedelta(hours=12)
if premium_start <= start_time < premium_end or previous_start <= start_time < previous_end:
premium_minutes += 1
else:
regular_minutes += 1
start_time += timedelta(minutes=1)
_premium_hours = premium_minutes / 60
_regular_hours = regular_minutes / 60
return _premium_hours, _regular_hours
datetime_01 = "06-11-2017 14:17"
datetime_02 = "06-11-2017 19:20"
datetime_03 = "05-11-2017 02:39"
datetime_04 = "11-11-2017 08:39"
print(is_premium_time_period(datetime_01, datetime_02))
print(is_premium_time_period(datetime_03, datetime_04))
EDIT: I'm sorry, I forgot to post what it returns:
It returns:
(0.3333333333333333, 4.716666666666667)
(76.35, 73.65)
Meaning (premium_hours, regular_hours)
How do I get the differences between two valid dates in weeks. I have googled many, but none are the one that I have been looking for
Say I have two dates:
02-Dec-2016 and 10-Jan-2017.
I want it to provide me with output like following
02-Dec-2016 - 04-Dec-2016 (2 days) (2 days before monday comes)
05-Dec-2016 - 08-Jan-2017 (5 weeks) (starts from monday-sunday)
08-Jan-2017 - 10-Jan-2017 (2 days) (2 days after monday has gone)
This is what you actualy want:
import datetime
def diff(d1, d2):
result = []
delta = datetime.timedelta(days=0)
day = datetime.timedelta(days=1)
while d1.weekday() != 0:
d1 += day
delta += day
result.append((d1 - delta, d1 - day))
weeks, days = divmod((d2 - d1).days, 7)
d3 = d1 + datetime.timedelta(weeks=weeks)
d4 = d3 + datetime.timedelta(days=days)
result.append((d1, d3 - day))
result.append((d3, d4))
return result
d1 = datetime.date(2016, 12, 2)
d2 = datetime.date(2017, 01, 10)
for i,j in diff(d1,d2):
print '{} - {} ({} days)'.format(datetime.datetime.strftime(i, "%d-%b-%Y"), datetime.datetime.strftime(j, "%d-%b-%Y"), (j-i).days + 1)
# 02-Dec-2016 - 04-Dec-2016 (3 days)
# 05-Dec-2016 - 08-Jan-2017 (35 days)
# 09-Jan-2017 - 10-Jan-2017 (2 days)
It is somewhat surprising how complicated it is to compute the difference between two times in Python. The following code is for differences in minutes, but you can modify this to weeks or other attributes.
# Compute the difference between two time values
import datetime
df = pd.DataFrame({'ATime1' : ['8/26/2016 10:00','8/26/2016 10:01','8/26/2016 10:02','8/26/2016 10:03'], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50], 'ATime2' : ['8/26/2016 10:01','8/26/2016 10:02','8/26/2016 10:03','8/26/2016 10:04']})
s1 = pd.Series(df['ATime1']) # Select one column of the dataframe and convert to a Series
s2 = pd.Series(df['ATime2'])
s1 = pd.to_datetime(s1) # Convert the Series object values to datetime values
s2 = pd.to_datetime(s2)
m1 = s1.dt.minute # Select minutes from the datetime values
m2 = s2.dt.minute
t1 = m1.loc[1] # Select the first minutes value in the column
t2 = m2.loc[1]
t1 = int(t1) # Convert minutes to integer
t2 = int(t2)
diff = t2 - t1
if t2 > t1:
print "ATime2 starts later than Atime1 by ", diff, " minute(s)."
else:
print "ATime1 starts later than Atime2 by ", diff, " minute(s)."
print t1, t2
Given a start time Timestamp('2015-05-06 09:40:45') and an end time Timestamp('2015-05-06 011:12:13'), I want to determine the number of minutes covered per hour of this duration.
That is, I want the following output:
hour 9 -- 19.25 minutes
hour 10 -- 60.00 minutes
hour 11 -- 12.22 minutes
I have an algorithm in mind, but I'm stumped comparing int and timestamp.
We are assuming that the start date and end date are the same.
from datetime import datetime
starttime = datetime(year = 2015, month = 5, day =6, hour=9, minute=40, second=45)
endtime = datetime(year = 2015, month = 5, day =6, hour=11, minute=12, second=13)
for i in range(starttime.hour, endtime.hour+1):
if i == starttime.hour:
rightbound = datetime(starttime.year, starttime.month, starttime.day, hour=(i+1), minute=0, second=0)
print starttime.hour, (rightbound - starttime).seconds/60.
elif i == endtime.hour:
leftbound = datetime(starttime.year, starttime.month, starttime.day, hour=(i), minute=0, second=0)
print leftbound.hour, (endtime - leftbound).seconds/60.
else:
print i, "60"
The (nth hour, # of minutes) output is:
9 19.25
10 60
11 12.2166666667