Python: give start and end of week data from a given date - python

day = "13/Oct/2013"
print("Parsing :",day)
day, mon, yr= day.split("/")
sday = yr+" "+day+" "+mon
myday = time.strptime(sday, '%Y %d %b')
Sstart = yr+" "+time.strftime("%U",myday )+" 0"
Send = yr+" "+time.strftime("%U",myday )+" 6"
startweek = time.strptime(Sstart, '%Y %U %w')
endweek = time.strptime(Send, '%Y %U %w')
print("Start of week:",time.strftime("%a, %d %b %Y",startweek))
print("End of week:",time.strftime("%a, %d %b %Y",endweek))
print("Data entered:",time.strftime("%a, %d %b %Y",myday))
out:
Parsing : 13/Oct/2013
Start of week: Sun, 13 Oct 2013
End of week: Sat, 19 Oct 2013
Sun, 13 Oct 2013
Learned python in the past 2 days and was wondering if there is a cleaner way to do this.This method works...it just looks ugly and It seems silly to have to create a new time variable for each date, and that there should be a way to offset the given date to the start and end of the week through a simple call but i have been unable to find anything on the internet or documentation that looks like it would work.

Use the datetime module.
This will yield start and end of week (from Monday to Sunday):
from datetime import datetime, timedelta
day = '12/Oct/2013'
dt = datetime.strptime(day, '%d/%b/%Y')
start = dt - timedelta(days=dt.weekday())
end = start + timedelta(days=6)
print(start)
print(end)
EDIT:
print(start.strftime('%d/%b/%Y'))
print(end.strftime('%d/%b/%Y'))

Slight variation if you want to keep the standard time formatting and refer to the current day:
from datetime import date, timedelta
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=6)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))

Use the pendulum module:
today = pendulum.now()
start = today.start_of('week')
end = today.end_of('week')

you can also use Arrow:
import arrow
now = arrow.now()
start_of_week = now.floor('week')
end_of_week = now.ceil('week')

pip install pendulum
import pendulum
today = pendulum.now()
start = today.start_of('week')
print(start.to_datetime_string())
end = today.end_of('week')
print(end.to_datetime_string())
found from here

Related

How do I find what the date will be next Sunday 12 am from now and then add 10 hours to it

I have this code
today = datetime.now().date()
# prints: 2022/1/14
rd = REL.relativedelta(days=1, weekday=REL.SU)
nextSunday = today + rd
#prints : 2022/1/16
How do i add 10 hours to the date so i can get a variable nextSunday_10am that i can substract to the current time
difference = nextSunday_10am - today
and schedule what I need to do
You can do the same thing as suggested by #Dani3le_ more directly with the following:
def getSundayTime(tme: datetime.date) -> datetime:
nxt_sndy = tme + timedelta(days= 6 - tme.weekday())
return datetime.combine(nxt_sndy, datetime.strptime('10:00', '%H:%M').time())
This will compute calculate the next Sunday and set time to 10:00
You can add hours to a DateTime by using datetime.timedelta().
nextSunday += datetime.timedelta(hours=10)
For example:
import datetime
today = datetime.datetime.today()
print("Today is "+str(today))
while today.weekday()+1 != 6: #0 = "Monday", 1 = "Tuesday"...
today += datetime.timedelta(1)
nextSunday = today + datetime.timedelta(hours=10)
print("Next sunday +10hrs will be "+str(nextSunday))

Calculating time intervals in Python, a more smarter way

was trying to calculate and a timedelta element with a str concatente, finally got it but feel there should be a smarter way to do this, any idea pls. here are my lines of code:
import datetime
import time
currentTime = datetime.datetime.now()
print("The time now is " + currentTime.strftime('%I:%M %p'))
realTime = currentTime.strftime('%I:%M:%S %p')
realTime was necessary to convert the datetime currentTime to a str to feed to strptime
print(realTime)
meetTime = input("Please input the meeting time in 12hrs timing")
# timeToMeet = datetime.datetime.strptime('11:50PM', '%I:%M%p').time()
timeToMeet = datetime.datetime.strptime(meetTime, '%I:%M%p')
tried both static and input time and they both worked
print(timeToMeet.strftime('%H:%M %p'))
timeNow = datetime.datetime.strptime(realTime, '%I:%M:%S %p')
print("The time now is " + timeNow.strftime('%I:%M%p'))
tdelta = timeToMeet - timeNow
print("Please, your meeting starts in " + str(tdelta))
print(tdelta)

How to make a count for each day passed from start date in python

I'm looking for a way to count each day passed from a start date in python. So if the start date was 21/02/2020 and count equals to 0, when the next day starts count should increment by 1.
Edit: After using Rusty's code I am able to show you a minimal reproducible example.
import datetime
start = datetime.datetime.strptime(input("Choose a start date (mm/dd/yyyy): "), '%m/%d/%Y')
current = datetime.datetime.now()
delta = current - start
count = delta.days
print(count)
import datetime
import time
count = 0
# "...from today..."
today = datetime.datetime.today()
# "...to infinity..."
while True:
now = datetime.datetime.today()
# "...as soon as the next day starts..."
if today.day != now.day:
# "...it would increment count by 1..."
count = count + 1
print(count)
today = now
time.sleep(1)
import datetime
today = datetime.datetime.strptime('03/21/2020', '%m/%d/%Y')
tomorrow = datetime.datetime.strptime('03/22/2020', '%m/%d/%Y')
next_saturday = datetime.datetime.strptime('03/28/2020', '%m/%d/%Y')
delta = tomorrow - today
count = delta.days
print(count)
delta = next_saturday - today
count = delta.days
print(count)

add a number of months to Datetime in Odoo 10

I want to create a module can do this : inputdate = "27 Feb 2017", nomonths = 2, so outputdate must be "27 April 2017". inputdate and nomonths are 2 fields we have to fill in, and ouputdate is just a "read-only" field in odoo.
class DateGenerate(models.Model):
_name = "studentmanagement.dategenerate"
inputdate = fields.Date()
nomonths = fields.Integer(required=True)
outputdate = fields.Date(readonly=True)
#api.onchange('inputdate','nomonths')
def add_month(self):
for record in self:
dt = fields.Datetime.to_string(record.inputdate)
inpYear = datetime.strptime(dt,"%Y")
inpMonth = datetime.strptime(dt,"%m")
inpDay = datetime.strptime(dt,"%d")
outYear = inpYear + int((inpMonth + record.nomonths - 1)/12)
outMonth = (inpMonth + record.nomonths - 1) % 12 + 1
record.outputdate = datetime.date(outMonth, inpDay, outYear)
I write the code based on the sources and explanations on the internet, but it does not work and causes the error :
I read the code and direction from these links
https://docs.python.org/2/library/datetime.html
https://github.com/odoo/odoo/blob/10.0/odoo/fields.py#L1504
To add/take months onto a date/datetime object I would suggest using the python package: dateutil.relativedelta. http://dateutil.readthedocs.io/en/stable/relativedelta.html
basic usage:
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
print date.today() + relativedelta(months=+3)
print datetime.today() + relativedelta(months=+3)
print date.today() - relativedelta(months=+3)
print datetime.today() - relativedelta(months=+3)
Your question references both datetime and date objects so have included examples for both.
Hope this helps.

Python human readable date difference

I have given date strings like these:
Mon Jun 28 10:51:07 2010
Fri Jun 18 10:18:43 2010
Wed Dec 15 09:18:43 2010
What is a handy python way to calculate the difference in days? Assuming the time zone is the same.
The strings were returned by linux commands.
Edit: Thank you, so many good answers
Use strptime.
Sample usage:
from datetime import datetime
my_date = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
print my_date
EDIT:
You could also print the time difference in a human readable form, like so:
from time import strptime
from datetime import datetime
def date_diff(older, newer):
"""
Returns a humanized string representing time difference
The output rounds up to days, hours, minutes, or seconds.
4 days 5 hours returns '4 days'
0 days 4 hours 3 minutes returns '4 hours', etc...
"""
timeDiff = newer - older
days = timeDiff.days
hours = timeDiff.seconds/3600
minutes = timeDiff.seconds%3600/60
seconds = timeDiff.seconds%3600%60
str = ""
tStr = ""
if days > 0:
if days == 1: tStr = "day"
else: tStr = "days"
str = str + "%s %s" %(days, tStr)
return str
elif hours > 0:
if hours == 1: tStr = "hour"
else: tStr = "hours"
str = str + "%s %s" %(hours, tStr)
return str
elif minutes > 0:
if minutes == 1:tStr = "min"
else: tStr = "mins"
str = str + "%s %s" %(minutes, tStr)
return str
elif seconds > 0:
if seconds == 1:tStr = "sec"
else: tStr = "secs"
str = str + "%s %s" %(seconds, tStr)
return str
else:
return None
older = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
newer = datetime.strptime('Tue Jun 28 10:52:07 2010', '%a %b %d %H:%M:%S %Y')
print date_diff(older, newer)
Original source for the time snippet.
#!/usr/bin/env python
import datetime
def hrdd(d1, d2):
"""
Human-readable date difference.
"""
_d1 = datetime.datetime.strptime(d1, "%a %b %d %H:%M:%S %Y")
_d2 = datetime.datetime.strptime(d2, "%a %b %d %H:%M:%S %Y")
diff = _d2 - _d1
return diff.days # <-- alternatively: diff.seconds
if __name__ == '__main__':
d1 = "Mon Jun 28 10:51:07 2010"
d2 = "Fri Jun 18 10:18:43 2010"
d3 = "Wed Dec 15 09:18:43 2010"
print hrdd(d1, d2)
# ==> -11
print hrdd(d2, d1)
# ==> 10
print hrdd(d1, d3)
# ==> 169
# ...
>>> import datetime
>>> a = datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y")
>>> b = datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")
>>> c = a-b
>>> c.days
10
This isn't along the same lines as the other answers, but it might be helpful to someone wanting to display something more human readable (and less precise). I did this quickly, so suggestions welcome.
(Note that it assumes until_seconds is the later timestamp.)
def readable_delta(from_seconds, until_seconds=None):
'''Returns a nice readable delta.
readable_delta(1, 2) # 1 second ago
readable_delta(1000, 2000) # 16 minutes ago
readable_delta(1000, 9000) # 2 hours, 133 minutes ago
readable_delta(1000, 987650) # 11 days ago
readable_delta(1000) # 15049 days ago (relative to now)
'''
if not until_seconds:
until_seconds = time.time()
seconds = until_seconds - from_seconds
delta = datetime.timedelta(seconds=seconds)
# deltas store time as seconds and days, we have to get hours and minutes ourselves
delta_minutes = delta.seconds // 60
delta_hours = delta_minutes // 60
## show a fuzzy but useful approximation of the time delta
if delta.days:
return '%d day%s ago' % (delta.days, plur(delta.days))
elif delta_hours:
return '%d hour%s, %d minute%s ago' % (delta_hours, plur(delta_hours), delta_minutes, plur(delta_minutes))
elif delta_minutes:
return '%d minute%s ago' % (delta_minutes, plur(delta_minutes))
else:
return '%d second%s ago' % (delta.seconds, plur(delta.seconds))
def plur(it):
'''Quick way to know when you should pluralize something.'''
try:
size = len(it)
except TypeError:
size = int(it)
return '' if size==1 else 's'
Here is an improved version of date_diff() routine by #the_void. It will print difference in the following fashion depending on how much the difference is:
1d
12 sec
30 min 12 sec
3h 30m
5d 3h 30m
Here is the routine:
def date_diff(newer, older):
if newer < older:
return '-1'
timeDiff = newer - older
days = int(timeDiff.days)
hours = int(timeDiff.seconds/3600)
minutes = int(timeDiff.seconds%3600/60)
seconds = int(timeDiff.seconds%3600%60)
str = ""
tStr = ""
if days > 0:
tStr = "d"
str = str + "%s%s " %(days, tStr)
if hours > 0:
tStr = "h"
str = str + "%s%s " %(hours, tStr)
if minutes > 0:
if days == 0 and hours == 0:
tStr = 'min'
str = str + "%s %s " %(minutes, tStr)
else:
tStr = "m"
str = str + "%s%s " %(minutes, tStr)
if days == 0 and hours == 0:
if seconds >= 0:
if days == 0 and hours == 0:
tStr = "sec"
str = str + "%s %s" %(seconds, tStr)
else:
tStr = 's'
str = str + "%s%s" %(seconds, tStr)
return str
Try this:
>>> (datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y") - datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")).days
10
from datetime import datetime
resp = raw_input("What is the first date ?")
date1 = datetime.strptime(resp,"%a %b %d %H:%M:%S %Y")
resp2 = raw_input("What is the second date ?")
date2 = datetime.strptime(resp2,"%a %b %d %H:%M:%S %Y")
res = date2-date1
print str(res)
For details on how to print a timedelta object better, you can see this previous post.

Categories