I want to calculate the difference in minutes between two datetimes.
My current code results in a timedelta of '1 day, 23:33:00'.
My question is how can I convert this to minutes (or generate the timedelta in minutes)?
import datetime
import time
kodate = '2019-01-13'
kotime = '14:15'
currdatetime = datetime.datetime.now()
currdate = currdatetime.strftime("%Y-%m-%d")
currtime = currdatetime.strftime("%H:%M")
datetimeFormat = '%Y-%m-%d %H:%M'
time1 = currdate + ' ' + currtime
time2 = kodate + ' ' + kotime
timedelta = datetime.datetime.strptime(time2, datetimeFormat) - datetime.datetime.strptime(time1, datetimeFormat)
print ('Timedelta: ' + str(timedelta))
So the current timedelta is 1 day 23 hours and 33 minutes, when I actually want 2853 (i.e. the actual number of minutes).
There's no direct method to return it in minutes, so just divide the number of seconds:
minutes = timedelta.total_seconds() / 60
Related
I'm trying to make a program that tells me how long there is (in minutes) until a certain time of day in the future. I've been trying to write working code all night, but I just can't wrap my head around strftime, timedelta and datetime. I'm quite new to python, and being able to do this would be quite useful to my day-to-day life; Can someone help me out?
from datetime import datetime
def minutes_until(hour, minute):
#get the current time
now = datetime.now()
#get the current hour
current_hour = now.hour
#get the current minute
current_minute = now.minute
#get the current second
current_second = now.second
#get the current microsecond
current_microsecond = now.microsecond
#get the time until the specified hour
time_until_hour = hour - current_hour
#get the time until the specified minute
time_until_minute = minute - current_minute
#get the time until the specified second
time_until_second = 60 - current_second
#get the time until the specified microsecond
time_until_microsecond = 1000000 - current_microsecond
#get the total time until the specified time
total_time = time_until_hour * 3600 + time_until_minute * 60 + time_until_second + time_until_microsecond / 1000000
#get the total time in minutes
total_time_in_minutes = total_time / 60
#return the total time in minutes
return total_time_in_minutes
print(minutes_until(15, 0)) #time now is 2 PM, how long until 15:00 (3PM)? = 60 minutes
You can try:
from datetime import datetime
target = '2023-01-01 00:00:00'
t = datetime.strptime(target, '%Y-%m-%d %H:%M:%S')
now = datetime.now()
print(f'{(t-now).total_seconds()/60:.0f} minutes')
output: 104445 minutes
I would like to ask for a help. I am a beginner when it comes to Python. I try to write a function, that sums up together two "times" and returns new_time and also how many times new_time passed midnight of "start_time"(for example 23:00 and 03:00, new_date is 02:00, and 1 day has passed )
Thank you really much in advance
from datetime import datetime, timedelta
def add_time(start_time: str, time_to_add: str):
start_time_time = datetime.strptime(start_time, "%H:%M")
add_time_time = datetime.strptime(time_to_add, "%H:%M")
new_time = start_time_time + timedelta(minutes=add_time_time.minute, hours=add_time_time.hour)
return f"New time is {new_time.strftime('%H:%M')}, XXX days after"
print(add_time("23:20", "19:20"))
Calculate the dates for start_time_time and new_time. The number of days elapsed will be the difference (in days) between these dates.
I believe there are several ways to extract just the date from a "datetime", but I have just replaced the hours and minutes to zero.
from datetime import datetime, timedelta
def add_time(start_time: str, time_to_add: str):
start_time_time = datetime.strptime(start_time, "%H:%M")
start_date = start_time_time.replace(hour=0, minute=0)
#print(start_date)
add_time_time = datetime.strptime(time_to_add, "%H:%M")
new_time = start_time_time + timedelta(minutes=add_time_time.minute, hours=add_time_time.hour)
new_date = new_time.replace(hour=0, minute=0)
#print(new_date)
days_elapsed = (new_date - start_date).days
return f"New time is {new_time.strftime('%H:%M')}, {days_elapsed} days after"
print(add_time("23:20", "19:20"))
The following code snippets demonstrates how to calculate the number of days after. You can uncomment the print statements to see what these dates actually represent.
Hope this helps.
There are many ways to do this, I done mine in such as way that it should allow you to add example of 100hours, etc. Hope this helps.
from datetime import datetime, timedelta
# Function that adds time HH:mm to a datetime object, adds set Hours and Minutes to start time and returns total days, hours, minutes and seconds passed
def add_time(start_time, time_to_add):
# Add time to start time
start_time = datetime.strptime(start_time, '%H:%M')
# Strip hours, minutes and convert to ms
time_to_add = time_to_add.split(':')
time_to_add = timedelta(hours=int(time_to_add[0]), minutes=int(time_to_add[1]))
finish_time = start_time + time_to_add
# Calculate total days, hours, minutes and seconds passed
total_days = finish_time.day - start_time.day
total_hours = finish_time.hour - start_time.hour
total_minutes = finish_time.minute - start_time.minute
total_seconds = finish_time.second - start_time.second
# Return total days, hours, minutes and seconds passed
return total_days, total_hours, total_minutes, total_seconds
# today + 23 hours + 20 minutes
days, hours, minutes, seconds = add_time("13:13", "25:00")
print(days, hours, minutes, seconds)
I have a time representation as string in the format:
9:00 am
8:45 pm
e.g., 12-hour, no leading hour 0, am/pm suffix
I need to get the time difference in minutes between then and now.
The time is always in the future, so if it's 09:00 right now, 9:10 am is in 10 mins time and 8:50 am is in 23h, 50m.
I've been playing with strptime but I can't seem to work out how to get my parsed time and now() in a compatible format to do arithmetic on.
something like this, indeed with strptime:
from datetime import datetime
timeString1 = "9:00 am"
timeString2 = "8:45 pm"
format = '%I:%M %p'
datetime1 = datetime.strptime(timeString1, format)
datetime2 = datetime.strptime(timeString2, format)
minutes_diff = (datetime2 - datetime1).total_seconds() / 60.0
print(f"the time difference in minutes is: {minutes_diff}")
this is a variant using datetime.
the format string FMT = "%I:%M %p" is selected according to strptime#time.strftime. and as only datetime objects support differences, i use those only (using datetime.combine).
from datetime import datetime, timedelta
FMT = "%I:%M %p"
TODAY_DATE = datetime.today().date()
def to_datetime(t_str):
return datetime.combine(TODAY_DATE, datetime.strptime(t_str, FMT).time())
NOW = to_datetime("9:00 am")
for t_str in ("9:10 am", "8:45 pm"):
t = to_datetime(t_str)
if t < NOW:
t += timedelta(days=1)
print(f"{t_str}, {(t - NOW)}, {(t - NOW).total_seconds() / 60:.0f} min")
it outputs:
9:10 am, 0:10:00, 10 min
8:45 pm, 11:45:00, 705 min
There are most likely better suited modules for that. But quick and dirty you could do:
def to_minutes(time_str)
time, suffix = time_str.split(" ")
hours, min = time.split(":")
if suffix == "pm":
hours+=12
min = hours*60+min
return min
time1 = to_minuntes("9:00 am")
time2 = to_minutes("8:45 pm")
diff = time2-time1
if diff < 0:
diff+= 24*60
# and if necessary you can do a
hours = diff //60
minutes = diff % 60
if hours > 0:
final_diff = f"{hours}h {minutes}min"
else:
final_diff = f"{minutes}min"
I'm trying to generate random list of 24hr timestamps. I can generate one sample of date and time between the set range using the code below. I'm hoping to generate multiple samples (e.g. 10 samples)
Also, the date component isn't a priority for me. If i could drop that and just generate random 24hr timestamps that would be good.
Most threads I've found only consider generate random dates. I can find anything that concerns time.
import random
import time
from datetime import datetime
def randomDate(start, end):
frmt = '%d-%m-%Y %H:%M:%S'
stime = time.mktime(time.strptime(start, frmt))
etime = time.mktime(time.strptime(end, frmt))
ptime = stime + random.random() * (etime - stime)
dt = datetime.fromtimestamp(time.mktime(time.localtime(ptime)))
return dt
random_datetime = randomDate("20-01-2018 13:30:00", "23-01-2018 04:50:34")
print(random_datetime)
Output:
2018-01-21 03:33:55
The whole point of the datetime library: datetime, timedelta, etc. objects act as much like numbers as possible, so you can just do arithmetic on them.
So, to generate a uniform distribution over a day, just take a uniform distribution from 0.0 to 1.0, and multiply it by a day:1
td = random.random() * datetime.timedelta(days=1)
To generate a uniform random time on some particular day, just add that to midnight on that day:
dt = datetime.datetime(2018, 5, 1) + random.random() * datetime.timedelta(days=1)
To generate a random timestamp between two timestamps:
dt = random.random() * (end - start) + start
And if you want 10 of those:
[random.random() * (end - start) + start for _ in range(10)]
That's all there is to it. Stay away from all those other time formats from the time module; they're only needed if you need compatibility with stuff like C libraries and filesystem data. Just use datetime in the first place:
def randomtimes(stime, etime, n):
frmt = '%d-%m-%Y %H:%M:%S'
stime = datetime.datetime.strptime(start, frmt)
etime = datetime.datetime.strptime(end, frmt)
td = etime - stime
return [random.random() * td + stime for _ in range(n)]
1. However, keep in mind that if you're dealing with local rather than UTC times, some days are actually 23 or 25 hours long, because of Daylight Saving Time. A timedelta doesn't understand that.
Depending on your needs, it might be well worth the trouble to learn the Python datetime and time modules. If your code will do lots of different manipulations, then go with #abarnert's answer. If all you need is a time string (rather than a Python timestamp), this function will crank it out for you:
import random
def randomTime():
# generate random number scaled to number of seconds in a day
# (24*60*60) = 86,400
rtime = int(random.random()*86400)
hours = int(rtime/3600)
minutes = int((rtime - hours*3600)/60)
seconds = rtime - hours*3600 - minutes*60
time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
return time_string
for i in range(10):
print(randomTime())
this outputs:
19:07:31
16:32:00
02:01:30
20:31:21
20:20:26
09:49:12
19:38:42
10:49:32
13:13:36
15:02:54
But if you don't want 24 hour time, then you can intercept the 'hours' variable before you stuff it in into the string:
import random
def randomTime():
# generate random number scaled to number of seconds in a day
# (24*60*60) = 86,400
rtime = int(random.random()*86400)
hours = int(rtime/3600)
minutes = int((rtime - hours*3600)/60)
seconds = rtime - hours*3600 - minutes*60
# figure out AM or PM
if hours >= 12:
suffix = 'PM'
if hours > 12:
hours = hours - 12
else:
suffix = 'AM'
time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
time_string += ' ' + suffix
return time_string
for i in range(10):
print(randomTime())
which gives :
05:11:45 PM
02:28:44 PM
08:09:19 PM
02:52:30 PM
07:40:02 PM
03:55:16 PM
03:48:44 AM
12:35:43 PM
01:32:51 PM
07:54:26 PM
In case you need continuous times:
from datetime import datetime,timedelta
time_starter = datetime.strptime("12:00:00","%H:%M:%S")
for i in range(1,10):
time = time_starter + timedelta(hours=i)
time = time.strftime("%H:%M:%S")
print(time)
if you need random or continuous minutes use:
time = time_starter + timedelta(minutes=i) #continuous
time = time_starter + timedelta(minutes=randint(0,60)) #random
import random
import time
from datetime import datetime
dates = []
def randomDate(start, end):
frmt = '%d-%m-%Y %H:%M:%S'
stime = time.mktime(time.strptime(start, frmt))
etime = time.mktime(time.strptime(end, frmt))
ptime = stime + random.random() * (etime - stime)
dt = datetime.fromtimestamp(time.mktime(time.localtime(ptime)))
return dt
for i in range(0 , 10)
dates.append(randomDate("20-01-2018 13:30:00", "23-01-2018 04:50:34"))
Your dates will have a list of 10 sample date :)
Good Luck
I want to know how many years, months, days, hours, minutes and seconds in between '2014-05-06 12:00:56' and '2012-03-06 16:08:22'. The result shall looked like: “the difference is xxx year xxx month xxx days xxx hours xxx minutes”
For example:
import datetime
a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'
start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')
diff = start – ends
if I do:
diff.days
It gives the difference in days.
What else I can do? And how can I achieve the wanted result?
Use a relativedelta from the dateutil package. This will take into account leap years and other quirks.
import datetime
from dateutil.relativedelta import relativedelta
a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'
start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')
diff = relativedelta(start, ends)
>>> print "The difference is %d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
The difference is 1 year 1 month 29 days 19 hours 52 minutes
You might want to add some logic to print for e.g. "2 years" instead of "2 year".
diff is a timedelta instance.
for python2, see:
https://docs.python.org/2/library/datetime.html#timedelta-objects
for python 3, see:
https://docs.python.org/3/library/datetime.html#timedelta-objects
from docs:
timdelta instance attributes (read-only):
days
seconds
microseconds
timdelta instance methods:
total_seconds()
timdelta class attributes are:
min
max
resolution
You can use the days and seconds instance attributes to calculate what you need.
for example:
import datetime
a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'
start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')
diff = start - ends
hours = int(diff.seconds // (60 * 60))
mins = int((diff.seconds // 60) % 60)