get the start and end timestamp of the current week in python - python

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

Related

Time to next full hour

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')))

How to add minutes to a datetime range comparison?

How can I alter the below to account for minutes as well as our in datetime range?
For example the below works fine.
from datetime import datetime
if (datetime.now().hour>=14) and (datetime.now().hour<=16):
print ('afternoon' )
else:
print ('not afternoon')
If the time now is past 14:30 but before 16:30 print afternoon.
You can use time from datetime to make timeobjects. So you can create a time object for your start time and a time object for your end time. then you can just extract the timeobject from you datetime and compare it with a simple between expression. I have used timedelta, to just manipulate the current date time to show this working.
from datetime import datetime, timedelta, time
datetimes = []
datetimes.append(datetime.now())
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
datetimes.append(datetimes[-1] + timedelta(hours=3, minutes=20))
start_time = time(14, 30)
end_time = time(16, 30)
for current in datetimes:
print(f"Time: {current.hour:02}:{current.minute:02}")
if start_time <= current.time() <= end_time:
print("afternoon")
else:
print("not afternoon")
OUTPUT
Time: 11:22
not afternoon
Time: 14:42
afternoon
Time: 18:02
not afternoon
from datetime import datetime, time
def checkTime(t):
if time(14, 30) <= t <= time(16, 30):
print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is afternoon" )
else:
print("time: " + t.strftime("%H") + "h" + " " + t.strftime("%M") + "m" + " is not afternoon" )
checkTime(time(15,15)) # time: 15h 15m is afternoon
checkTime(time(14,30)) # time: 14h 30m is afternoon
checkTime(time(15,31)) # time: 15h 31m is afternoon
checkTime(time(14,29)) # time: 14h 29m is not afternoon
checkTime(time(16,31)) # time: 16h 31m is not afternoon
checkTime(time(18,10)) # time: 18h 10m is not afternoon

Getting number of Hours between a Date-Time Range in Python

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))

A simple mathematic Operation python

I have a method which returns the number of days within a specified range and excluding some specific days like Friday. here is an example if you take out friday and thursday, from 2016-8-6 to 2016-9-6 the result will be 8 days holiday and 24 working day. in case i want to do the reverse operation how do i find the end date (2016-9-6) if i have only working days and start date.
from datetime import datetime, timedelta
def measure_workingdays(start_date, end_date, off_days):
format = "%Y-%m-%d"
if not isinstance(start_date, datetime):
start_date = datetime.strptime(start_date, format)
if not isinstance(end_date, datetime):
end_date = datetime.strptime(end_date, format)
total_days = (end_date - start_date).days + 1 # + 1 Because it count one day less
holiday = 0
start = start_date
for rec in range(total_days):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # 8
working_days = total_days - holiday
print(working_days) # 24
start_date = "2016-8-6"
start_date = datetime.strptime(start_date, "%Y-%m-%d")
end_date = "2016-9-6"
end_date = datetime.strptime(end_date, "%Y-%m-%d")
off_day = ['Fri','Thu']
working_days = measure_weekdays(start_date, end_date, off_day)
Example of Reverse operation
def measure_weekdays_reverse(start_date, paid, off_days):
format = "%Y-%m-%d"
if not isinstance(start_date, datetime):
start_date = datetime.strptime(start_date, format)
holiday = 0
start = start_date
for rec in range(paid):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # Output 6 instead of 8
last_paid_date = start + timedelta(days=holiday)
print(last_paid_date) # output 2016-09-05 insteaad of 2016-09-06
total_days = measure_weekdays_reverse(start_date, 24, ["Fri","Thu"])
The error is that you only loop a fix number of times (the number of paid days), so if you encounter holidays, you will in fact not iterate enough to find all the true paid days, which may still hide some holidays.
You can fix this by adding an inner loop on the holidays. Change this:
for rec in range(paid):
day = start.strftime("%a")
if day in off_days:
holiday += 1
start += timedelta(days=1)
print(holiday) # Output 6 instead of 8
last_paid_date = start + timedelta(days=holiday)
to this:
for rec in range(paid):
day = start.strftime("%a")
while day in off_days:
holiday += 1
start += timedelta(days=1)
day = start.strftime("%a")
last_paid_date = start
start += timedelta(days=1)
print(holiday)

calculate dates in python

def main(filename, from_str, to_str):
date_from =time.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = time.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
if __name__ == "__main__":
if len(sys.argv) < 1:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
sys.exit(1)
main("servanet-" + sys.argv[1] + sys.argv[2]+ ".txt", sys.argv[1] + " 00:00", sys.argv[2] + " 23:59")
This is part of my code, I want to calculate the days from the input, (I don't need to calculate minutes and seconds,just days in this case, but I will use the minute and the second information later in the code, so I need to keep them like this) ,but it seems, (date_from - date_to).days cannot work with minutes and seconds after it, how can I solve this problem?
Many thanks!
========comments: I think I cannot simply use day2-day1. since if they are from different month, the result will be wrong, like from 2011-08-01 to 2011-09-02
Use datetime.datetime.strptime instead of time.strptime:
time.striptime returns a time.struct_time object which does not support subtraction. In contrast, datetime.datetime.strptime returns a datetime.datetime object, which does support date arithmetic.
import datetime as dt
def main(filename, from_str, to_str):
date_from = dt.datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = dt.datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_from - date_to).days
print days
yields
% test.py '2011-09-08' '2011-10-08'
2011-09-08 00:00:00 2011-10-08 23:59:00
-31
By the way, sys.argv is always at least of length 1. The first item is the name of the calling program. So I think you need
if __name__ == "__main__":
if len(sys.argv) <= 2:
print "Usage: %s DATE [e.g. 2011-09-08 2011-10-08]"
instead of if len(sys.argv) < 1.
import datetime
import time
def parse_date(date_str):
if ' ' in date_str:
return time.strptime(date_str, "%Y-%m-%d %H:%M")
else:
return time.strptime(date_str, "%Y-%m-%d")
def main(filename, from_str, to_str):
date_from = parse_date(from_str)
date_to = parse_date(to_str)
print date_from, date_to
days = (datetime.date(*date_to[:3]) - datetime.date(*date_from[:3])).days
print days
I am not sure what you mean "cannot with minutes and seconds" after it. But I modified your function a little bit and it should be fine:
def main(filename, from_str, to_str):
date_from = datetime.strptime(from_str, "%Y-%m-%d %H:%M")
date_to = datetime.strptime(to_str, "%Y-%m-%d %H:%M")
print date_from, date_to
days = (date_to - date_from).days
print days
main("", "2011-09-08 00:00", "2011-10-09 00:00")
main("", "2011-09-08 00:00", "2011-10-08 23:59")
main("", "2011-09-08 00:00", "2011-10-08 00:00")
>>> 2011-09-08 00:00:00 2011-10-09 00:00:00
31
2011-09-08 00:00:00 2011-10-08 23:59:00
30
2011-09-08 00:00:00 2011-10-08 00:00:00
30

Categories

Resources