I have a timestamp like the following:
Timestamp('2022-01-01 19:55:00')
How do i get the time difference to the next full hour (in minutes)?
So in this example the output should be 5 minutes.
You'll need to use the datetime lib :
from datetime import datetime, timedelta
def time_to_next_hour(timestamp):
current_time = datetime.strptime(str(timestamp), '%Y-%m-%d %H:%M:%S')
next_hour = current_time.replace(microsecond=0, second=0, minute=0) + timedelta(hours=1)
time_diff = next_hour - current_time
return int(time_diff.total_seconds() / 60)
print(time_to_next_hour(Timestamp('2022-01-01 19:55:00')))
Related
how i can do the checking. so that if the time which i write in the h m s format hasnt yet come, add yesterdays date to it
for example:
now 00:10:15 , i input 00:15:15 bot write 2022-09-09 00:15:15
and if the time has come to add todays
for example:
now 00:10:15 , i input 00:10:00 , bot write 2022-09-10 00:10:00
from datetime import datetime, timezone
import time
from zoneinfo import ZoneInfo
import pytz
#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))
newYorkTz = pytz.timezone("Europe/Kiev")
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d ')
#date = datetime.today().strftime('%Y-%m-%d ')
from_date = str(input('time): '))
fulldate = timeInNewYork + from_date
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp()
print(epoch)
You need to add an if.. else statement to check if the input time has passed (compared to the actual time) or not. If so, you can use timedelta to add one day and get your timestamp.
Try this :
from datetime import datetime, timezone, timedelta
import time
from zoneinfo import ZoneInfo
import pytz
#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))
newYorkTz = pytz.timezone("Europe/Kiev")
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d')
#date = datetime.today().strftime('%Y-%m-%d ')
now = datetime.now(newYorkTz)
from_date = str(input('time): '))
my_datetime = datetime.strptime(from_date, "%H:%M:%S")
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
fulldate = timeInNewYork + ' ' + from_date
if (now > my_datetime):
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp()
else:
dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S') + timedelta(days=-1)
epoch = dt.timestamp()
print(dt)
print(epoch)
>>> Test with a past time
time): 11:55:33
2022-09-10 11:55:33
1662803733.0
>>> Test with a future time
time): 19:00:33
2022-09-09 19:00:33
1662915633.0
def dailyChecksInputDates():
current_date = datetime.now()
weekday = current_date.strftime("%A")
if weekday.upper() == 'MONDAY':
return datetime.now() - timedelta(days=3)
else:
return datetime.now() - timedelta(days=1)
print(ParametersUtil.dailyChecksInputDates())
Here date is returning right. But I need the time should be returning always 09:00:00. Any chances of returning as required?
Use replace of datetime module.
current_date = datetime.now().replace(hour=9, minute=0, second=0)
While creating current date use the combine function of datetime:
datetime.combine(datetime.date.today(), datetime.time(9, 0, 0))
datetime.date.today() - this will give you the current date
datetime.time(9, 0, 0) - this will give you 09:00:00
I need to get the timestamps in milliseconds based on the current day. The start timestamp must be Monday 00:00 (start of the day of the current week) and the end timestamp should be the end of the week which in my case ends with Friday 23:59. I have an implementation that does not give the timestamps from 00:00 to 23:59 maybe you can help me change my solution
.
from datetime import date, datetime, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=4)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
You can use datetime.replace():
from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
output
Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Start with a datetime to include time fields, but create it only from the year, month, day values of the date.today().
Subtract the current weekday to get to Monday 0:0:0.
Add 5 days to get to Saturday 0:0:0 and subtract 1 minute to get to Friday 23:59:00.
from datetime import date, datetime, timedelta, time
# use a datetime to get the time fields but init it just with a date to default to 0:0:0
today = datetime(date.today().year, date.today().month, date.today().day)
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=5) - timedelta(minutes=1)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))
Output:
Today: 2021-07-08 21:55:41.062506
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00
Something like this works:
from datetime import date, datetime, time
today = date.today()
week_start = datetime(today.year,
today.month,
today.day - today.weekday())
week_end = datetime(today.year,
today.month,
today.day + 7 - today.weekday(),
time.max.hour,
time.max.minute,
time.max.second,
time.max.microsecond)
print(week_start, week_end)
It gives:
2021-07-05 00:00:00 2021-07-11 00:00:00
So I'm trying to print the total hours in intervals between a start date and an end date in python as follows:
#app.route('/test/')
def test():
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def daterange(start_date_time, end_date_time):
for n in range(int ((end_date_time - start_date_time).days)):
yield start_date_time + timedelta(n)
for single_date in daterange(start_date_time, end_date_time):
def get_delta(start_date_time, end_date_time):
delta = end_date_time - start_date_time
return delta
# Split time in hours
delta = get_delta(start_date_time,end_date_time)
for i in range(delta.days * 24 + 1): # THIS IS ONLY CALCULATING 24HRS FROM TIME GIVEN START TIME NOT TILL THE SELECTED END TIME SO I'M ONLY GETTING AN EXACT 24 HOUR RANGE
currtime = start_date_time + timedelta(hours=i)
print (currtime)
return ("done")
By This i'm only managing to get the first 24 Hours from the selected date, but I wish to keep on counting and get all hours till the selected end date.
You might be overthinking it.
from datetime import datetime, timedelta
date_format = "%Y-%m-%d %H:%M:%S"
start_date_time = datetime.strptime("2018-10-16 07:00:00", date_format)
end_date_time = datetime.strptime("2018-10-18 22:00:00", date_format)
def get_delta(l, r):
return abs(int((l-r).total_seconds())) / 3600
for h in range(int(get_delta(start_date_time, end_date_time))):
print((start_date_time + timedelta(0, h*3600)).strftime(date_format))
I tried to develop a Python function that determines the difference between two datetime objects. I need an algorithm that calculates the number of hours per day. Is there a built-in function for this?
from datetime import datetime, timedelta, date
def getHoursByDay(dateA, dateB):
...
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
hours = getHoursByDay(dateA, dateB)
print hours
# {
# '2018-09-01': 15,
# '2018-09-02': 24,
# '2018-09-03': 11.5,
# }
There is no built-in function, though it is very simple to build one.
from datetime import datetime, timedelta, time
def deltaByDay(dateA, dateB):
dateAstart = datetime.combine(dateA, time())
dateBstart = datetime.combine(dateB, time())
result = {}
oneday = timedelta(1)
if dateAstart == dateBstart:
result[dateA.date()] = dateB - dateA
else:
nextDate = dateAstart + oneday
result[dateA.date()] = nextDate - dateA
while nextDate < dateBstart:
result[nextDate.date()] = oneday
nextDate += oneday
result[dateB.date()] = dateB - dateBstart
return result
def deltaToHours(delta, ndigits=None):
return delta.days * 24 + round(delta.seconds / 3600.0, ndigits)
dateA = datetime.strptime('2018-09-01 09:00:00', '%Y-%m-%d %H:%M:%S')
dateB = datetime.strptime('2018-09-03 11:30:00', '%Y-%m-%d %H:%M:%S')
deltas = deltaByDay(dateA, dateB);
output = {k.strftime('%Y-%m-%d'): deltaToHours(v, 1) for k, v in deltas.items()}
print(output)
# => {'2018-09-01': 15.0, '2018-09-02': 24.0, '2018-09-03': 11.5}
The built in timedelta functions would be able to get you the total days, and the remaining hours difference. If you want the output specifically in that dictionary format posted you would have to create it manually like this:
from datetime import datetime, time, timedelta
def getHoursByDay(dateA, dateB):
if dateA.strftime("%Y-%m-%d") == dateB.strftime("%Y-%m-%d"):
return {dateA.strftime("%Y-%m-%d"): abs(b-a).seconds / 3600}
result = {}
delta = dateB - dateA
tomorrow = dateA + timedelta(days=1)
day1 = datetime.combine(tomorrow, time.min) - dateA
result[dateA.strftime("%Y-%m-%d")] = day1.seconds / 3600
for day in range(1, delta.days):
result[(dateA + timedelta(days=day)).strftime("%Y-%m-%d")] = 24
priorday = dateB - timedelta(days1)
lastday = dateB - datetime.combine(priorday, time.min)
result[dateB.strftime("%Y-%m-%d")] = lastday.seconds / 3600
return result
Essentially this function calculates the first day and the last day values, then populates all the days in between with 24.
There is a kind of simple way to do this.
hours = (dateA - dateB).hours
I've used this to caclulate a difference in days.
https://docs.python.org/2/library/datetime.html#datetime.timedelta