TypeError: strptime() argument 1 must be str, not datetime.date
I'm getting the above error when I run the below code. Do you have any idea about this ?
import datetime
from datetime import datetime, timedelta
import babel
import time
date_format = "%Y-%m-%d"
class HrPayslipEmployees(models.TransientModel):
_inherit = 'hr.payslip.employees'
#api.one
def compute_date_diff(self, ds, dt):
from datetime import datetime
d1 = datetime.strptime(ds, "%Y-%m-%d")
d1 = str(d1)
d2 = datetime.strptime(dt, "%Y-%m-%d")
d2 = str(d2)
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
But the same code is perfectly working in the Pythin 2.7 , but the above code is I run on Python 3.x
Imported libraries for the program are also mentioned above.
Thanks in advance. The complete code is just above here.
import datetime
from datetime import datetime, timedelta
date_format = "%Y-%m-%d"
def compute_date_diff( ds, dt):
d1 = datetime.strptime(ds, "%Y-%m-%d")
d2 = datetime.strptime(dt, "%Y-%m-%d")
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
print(compute_date_diff("2019-03-24","2019-03-25"))
This is working fine in python3. You don't need to convert d1 and d2 to string for finding days.
You do not have to convert the date to str:
In Python 3.x:
from datetime import datetime
def compute_date_diff(ds, dt):
d1 = datetime.strptime(ds, "%Y-%m-%d")
d2 = datetime.strptime(dt, "%Y-%m-%d")
days = (d2 - d1).days + 1
if days < 0:
days = 0
return days
print(compute_date_diff('2019-01-01', '2019-02-01'))
OUTPUT:
32
Let me answer in Odoo context. With this commit your old code isn't working anymore. Because before that, you got strings as values for Date and Datetime fields in Odoo. As of this commit you get python datetime.date resp. datetime.datetime objects instead.
So just use these objects and don't parse into or from strings if not needed.
Related
I am currently trying to construct a function that takes a date string and returns the number of days from that date until now. It will return 0 if it detects that the format is wrong, with the input date string format being Day/Month/Year (e.g. 12/3/21). The number should be negative if it is a past date (e.g. today is 14/3/21, the input date is 3/3/21, the function should return -11). This is my code so far but it keeps returning 0:
from datetime import datetime
from datetime import date
def convert_date(input_date):
try:
current_date = date.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
d2 = datetime.strptime(current_date, '%d/%m/%y')
delta = d1 - d2
return delta.day
except:
return 0
I am very unsure on what I have done wrong, as I have done a lot of research but have not found a solution. Hopefully someone can provide further clarification, thanks
(Also i am using the Datetime package)
These are basics and you need to understand datetime module well. Hope this solves your problem.
from datetime import datetime
def convert_date(input_date):
try:
current_date = datetime.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
delta = d1 - current_date
return delta.days
except ValueError:
return 0
From what I've seen this should be working even if it's not the prettiest. I've tried plenty of things but doesn't seem to work with anything and best I've been able to do is change the error message lol.
try:
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
Try the following:
from datetime import timedelta
import datetime as dt
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1 = d1.strftime('%Y%m%d') # I changed this line
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
strftime() returns the string, it does not convert the date itself to a string.
I modified your code a little. There were a couple of mistake in it and it wasn't running.
The main problem you were running into is you were trying to concatenate a string with a datetime object. You applied the strftime correctly but you didn't save the string. That string you can concatenate with another string.
import datetime as dt
date = dt.datetime.now()
d1 = date - dt.timedelta(days=1)
d1_string = d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol{timestamp}.txt'.format(timestamp=d1_string)
In your code you don't assign result of datetime.strftime() to a variable. Solution is simple:
from datetime import datetime, timedelta
current_date = datetime.now() # store current date and time
required_date = current_date - timedelta(days=1) # substitute 1 day
str_date = required_date.strftime('%Y%m%d') # apply formatting
url = f'http://regsho.finra.org/FNQCshvol{str_date}.txt'
You can also do it in one line (which makes code much less readable):
url = f"http://regsho.finra.org/FNQCshvol{(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')}.txt"
I'm trying to find the difference in months between two dates using relativedelta. I'm able to find the difference in years and days but I get 0 when I filter on months. Any suggestions?
from dateutil import relativedelta as rd
import datetime as date
dateformat = '%Y/%m/%d'
startDate = date.strptime('2017/07/01',dateformat).date()
endDate = date.strptime('2019/10/29',dateformat).date()
date_diff = rd.relativedelta(endDate,startDate)
print(date_diff.days)
relativedelta shows the difference as years, months, and days. It's not going to show net months if that's what you're looking for. If two dates happen to be on the same month in different years the months attribute will be zero.
If you want to show the total months, you can write a small function that does that for you by adding in the years value.
from datetime import datetime
from dateutil.relativedelta import relativedelta
def month_delta(start_date, end_date):
delta = relativedelta(end_date, start_date)
# >>> relativedelta(years=+2, months=+3, days=+28)
return 12 * delta.years + delta.months
d1 = datetime(2017, 7, 1)
d2 = datetime(2019, 10, 29)
total_months = month_delta(d1, d2)
print(total_months)
# >>> 27
Here's the solution:
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12
end-start will produce timedelta object on which days attribute will gve the required days difference
>>> from datetime import date
>>> start = date(2017,7,1)
>>> end = date(2017,11,11)
>>> (end-start).days
133
As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday
I have two different dates and I want to know the difference in days between them. The format of the date is YYYY-MM-DD.
I have a function that can ADD or SUBTRACT a given number to a date:
def addonDays(a, x):
ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600))
return ret
where A is the date and x the number of days I want to add. And the result is another date.
I need a function where I can give two dates and the result would be an int with date difference in days.
Use - to get the difference between two datetime objects and take the days member.
from datetime import datetime
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
Another short solution:
from datetime import date
def diff_dates(date1, date2):
return abs(date2-date1).days
def main():
d1 = date(2013,1,1)
d2 = date(2013,9,13)
result1 = diff_dates(d2, d1)
print '{} days between {} and {}'.format(result1, d1, d2)
print ("Happy programmer's day!")
main()
You can use the third-party library dateutil, which is an extension for the built-in datetime.
Parsing dates with the parser module is very straightforward:
from dateutil import parser
date1 = parser.parse('2019-08-01')
date2 = parser.parse('2019-08-20')
diff = date2 - date1
print(diff)
print(diff.days)
Answer based on the one from this deleted duplicate
I tried the code posted by larsmans above but, there are a couple of problems:
1) The code as is will throw the error as mentioned by mauguerra
2) If you change the code to the following:
...
d1 = d1.strftime("%Y-%m-%d")
d2 = d2.strftime("%Y-%m-%d")
return abs((d2 - d1).days)
This will convert your datetime objects to strings but, two things
1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and
2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings
What I found is that you literally only need the following:
import datetime
end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)
print difference_in_days
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
I tried a couple of codes, but end up using something as simple as (in Python 3):
from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])
If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.
If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):
df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date
And then run:
df['difference_in_days'] = abs(df['end_date'] - df['start_date'])
pd.date_range('2019-01-01', '2019-02-01').shape[0]