x=['2020-05-12 20:16', '2020-05-12 20:16', '2020-05-10 20:11', '2020-05-10 20:07', '2020-05-11 20:03', '2020-05-8 20:02', '2020-05-8 20:02', '2020-05-9 20:02',]
#staticmethod
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
past = datetime.now() - date_object
How can I edit my function so that it returns True if the date not older than yesterday (within 24 hours of current time) else returns False, I feel I am half way there but not sure what to do next.
You need to quantify the difference between 2 datetime object, timedelta is here that
A timedelta object represents a duration, the difference between two dates or times.
You want our duration to be lower than 24h/1d so you need < timedelta(days=1) or < timedelta(hours=24)
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
past = datetime.now() - date_object
return past < timedelta(days=1) # from datetime import timedelta
test the difference datetime.now() - date_object against a timedelta of 1 day:
from datetime import datetime, timedelta
x = ['2020-05-12 20:16', '2020-05-12 20:16', '2020-05-10 20:11',
'2020-05-10 20:07', '2020-05-11 20:03', '2020-05-8 20:02',
'2020-05-8 20:02', '2020-05-9 20:02',]
def compare_time(post_time):
date_object = datetime.strptime(post_time, "%Y-%m-%d %H:%M")
return (datetime.now() - date_object) < timedelta(days=1)
for t in x:
print(t, compare_time(t))
# 2020-05-12 20:16 True
# 2020-05-12 20:16 True
# 2020-05-10 20:11 False
# 2020-05-10 20:07 False
# 2020-05-11 20:03 False
# 2020-05-8 20:02 False
# 2020-05-8 20:02 False
# 2020-05-9 20:02 False
Related
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))
I want to specify the date of the desired format as a file name in this way
;
During [2019-10-01 09:00 ~ 2019-10-02 08:59:59]
Save data to 191001-09.txt
I have no idea about this. I could only follow simple code.
Please let me know how to fix it :
def timeStamped (fname, fmt = '19% m% d-% H {fname} '):
return datetime.datetime.now (). strftime (fmt) .format (fname = fname)
with open (timeStamped ('. txt'), 'a') as f_last:
f_last.write ('data')
Question: Conditional file name from datetime.now()
Import the required objects
datetime
timedelta
from datetime import datetime, timedelta
Define a function that gets the desired file name from a datetime.date object:
def fname_from_date(date):
# Rule 09:00:00 ~ day + 1 08:59:59
midnight = date.replace(hour=0, minute=0, second=0)
begin_of_day = date.replace(hour=9, minute=0, second=0)
end_of_day = date.replace(hour=8, minute=59, second=59)
# Are we between 'midnight' and 'end_of_day'
if date >= midnight and date <= end_of_day:
date = date - timedelta(days=1)
print('\tNext day -1: {}'.format(date))
# 191001-09.txt
fname = date.strftime('%Y%m%d-09')
return fname
Test the function def fname_from_date(... with static dates.
This requires to create a datetime.date object from datestr.
for datestr in ['2019-10-01 09:00:00',
'2019-10-01 11:01:11',
'2019-10-02 07:07:07',
'2019-10-02 08:59:59']:
date = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
print(date)
fname = '{}.txt'.format(fname_from_date(date))
print('\t{}'.format(fname))
Output:
2019-10-01 09:00:00
20191001-09.txt
2019-10-01 11:01:11
20191001-09.txt
2019-10-02 07:07:07
Next day -1: 2019-10-01 07:07:07
20191001-09.txt
2019-10-02 08:59:59
Next day -1: 2019-10-01 08:59:59
20191001-09.txt
Usage:
fname = '{}.txt'.format(fname_from_date(datetime.now()))
I need to calculate the months between two dates. I know it can be easy but I have a code and I can not complete it.
start_date=fields.Date(string="Startdate", requiered=True)
end_date=fields.Date(string="End_date", requiered=True)
duration=fields.Char(string="Duration", computer="_duration")
#api.multi
#api.depends('start_date','end_date')
def _duration(self):
if self.start_date and self.end_date:
start_dt = fields.Datetime.from_string(self.start_date)
finish_dt = fields.Datetime.from_string(self.end_date)
difference = relativedelta(finish_dt, start_dt)
month = difference.month
Try using this code
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
or
from datetime import datetime
from dateutil import relativedelta
def get_months(d1, d2):
date1 = datetime.strptime(str(d1), '%Y-%m-%d')
date2 = datetime.strptime(str(d2), '%Y-%m-%d')
print (date2, date1)
r = relativedelta.relativedelta(date2, date1)
months = r.months + 12 * r.years
if r.days > 0:
months += 1
return months
month = get_months('2018-08-13','2019-06-30')
print(month)
Try this code
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2019-03-01'), '%Y-%m-%d')
date2 = datetime.strptime(str('2019-07-01'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
print(r.months)
how can i convert my string of date to a datetime.timedelta() in Python?
I have this code :
import datetime
date_select = '2011-12-1'
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
thanks in advance ...
You wouldn't convert date_select to a timedelta, instead, you need a datetime object, which can be added to a timedelta to produce an updated datetime object:
from datetime import datetime, timedelta
date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
Or, if you prefer, without the fancy from ... import ... import line:
import datetime # <- LOOK HERE, same as in your example
date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
You use strptime to do this.
from datetime import datetime
target_date = datetime.strptime(date_select, '%Y-%m-%d')
from datetime import datetime, timedelta
date_select = '2011-12-1'
new_data = datetime.strptime(date_select, '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
You will get 2011-12-02 00:00:00; to strip off the '00:00:00' and get only the date, just add .date() to target_date
print target_date.date()
This should give you the only the date = 2011-12-02
How to get saturday and sunday dates from given date range.
for example :
start_date = 2011-09-01
end_date = 2011-09-15
Now it should give the out put
2011-09-03
2011-09-04
2011-09-10
2011-09-11
Any help really appreciate.
>>> import datetime
>>> start = datetime.datetime.strptime("2011-09-01", "%Y-%m-%d")
>>> end = datetime.datetime.strptime("2011-09-15", "%Y-%m-%d")
>>> while start <= end:
... if start.weekday() in (5, 6):
... print start.strftime("%Y-%m-%d")
... start += datetime.timedelta(days=1)
...
2011-09-03
2011-09-04
2011-09-10
2011-09-11
>>>
Well, I think this should work:
from datetime import datetime, timedelta
def daterange(start_date, end_date):
for n in range((end_date - start_date).days):
yield start_date + timedelta(n)
start_date = '2011-09-01'
end_date = '2011-09-15'
format = '%Y-%m-%d'
start_date_object = datetime.strptime(start_date, format)
end_date_object = datetime.strptime(end_date, format)
for day in daterange(start_date_object, end_date_object):
if day.weekday() in [5, 6]:
print day.strftime(format)