I'm trying to find out the age of a person in 'days' by taking away 'current date' from 'birth date'.
For example, on python I could successfully use this code:
from datetime import date
date1 = date(2021, 7, 16)
date2 = date(2021, 8, 20)
numberDays = d1 - d0
print(numberDays.days)
Output:
35 days old.
But when I try to find out the 'current' date using datetime:
from datetime import datetime
birth = datetime(2021,8,19)
current = datetime.today().strftime('%Y, %m, %d')
age = (current - birth)
Output 2:
age = (current - birth) TypeError: unsupported operand type(s) for -:
'str' and 'datetime.datetime'
I'm not very sure what data type to convert the two variable into to get the same desired result as the first example code.
Thank you in advance.
When you subtract one datetime object from another, you get an object of type "datetime.timedelta".
From this type you can access to many properties and methods.
See here :
https://docs.python.org/3/library/datetime.html
Therefore, to take your example :
import datetime as dt
birth = dt.datetime(2020, 8, 20)
# Substract the date (the result has the type datetime.timedelta)
age = dt.datetime.today() - birth
# show the days property
print(age.days)
Your error message comes from the fact you try to substract a datetime object from a string.
because:
current = datetime.today().strftime('%Y, %m, %d')
is a string (string from a time)
Related
I am trying to set a function that subtracts a month from an specific date format as an argument, and returns a date in the same specific date format,
This argument is given by today's month and year: 01/%m/%Y.
Actual code:
from datetime import datetime
import dateutil.relativedelta
actual_date = datetime.now()
actual_date = "{}/{}/{}".format('01', actual_date.month, actual_date.year)
def set_date(actual_date):
print(actual_date - dateutil.relativedelta.relativedelta(months=1))
Here's the output when set_date() is tested:
set_date(actual_date)
TypeError: unsupported operand type(s) for -: 'str' and 'relativedelta'
Expected output should look like this:
01/12/2020
You're doing it in the wrong order. Perform the date calculation first, and then convert to a string.
now = datetime.now()
one_month_ago = now - dateutil.relativedelta.relativedelta(months=1)
print("{}/{}/{}".format('01', one_month_ago.month, one_month_ago.year))
In the first line, you get a datetime, then in the second line you build a string out of it. As a result, in set_date you get the mentioned error.
I suggest that you remove the second line and simply give the datetime object to set_date and do a strftime on the result:
actual_date = datetime.now()
def set_date(actual_date):
result = actual_date - dateutil.relativedelta.relativedelta(months=1)
print(datetime.strftime(result, "01/%m/%Y"))
However, if you really want to keep those conversions, you can use strptime for that purpose.
actual_date = datetime.now()
actual_date = datetime.strptime("{}/{}/{}".format('01', actual_date.month, actual_date.year), "%d/%m/%Y")
def set_date(actual_date):
result = actual_date - dateutil.relativedelta.relativedelta(months=1)
print(datetime.strftime(result, "%d/%m/%Y"))
Both types of data have been converted into dates, and it still is telling me it can't subtract them. I've watched many tutorials and looked at stack overflow for hours, but all the solutions say that the only possible problem is an incorrect form of data which is not true. The error message is :
>unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'<
The text file contains only this:
Birthday 30/5/2021
def display():
with open ('countdown.txt', 'r') as file:
for line in file:
data = line.split(' ')
title = data[0]
date_str = data[1]
date = datetime.datetime.strptime(date_str, '%d/%m/%y')
time_between = datetime.date.today()-date
print(title + 'is' + time_between + 'days away!')
display()
One value is date+time and one is date only, they do not match. Replace datetime.date.today() with datetime.datetime.today().
The result will be a datetime.timedelta object.
There are two different date methods, one in datetime and one in date:
import datetime
dt = datetime.datetime.today()
print(dt, type(dt))
# 2020-12-10 20:45:20.661116 <class 'datetime.datetime'>
d = datetime.date.today()
print(d, type(d))
# 2020-12-10 <class 'datetime.date'>
As your date is a datetime object, you need to subtract it with another datetime, so you have to use:
time_between = datetime.datetime.today() - date
I want to find the week number of a date column in my datasets. The date is in the format "2020-09-27 07:14:01.114051200". However I could not convert to week number.
I tried the below code:
date=mydate.strftime("%W")
I'm getting this error: AttributeError: 'Series' object has no attribute 'strftime'
You need to first convert your date in string form to a datetime object. Then you can ask for the week number from that object.
import datetime
datestr = "2020-09-27 07:14:01.114051200"
mydate = datetime.datetime.strptime(datestr.split('.')[0] , '%Y-%m-%d %H:%M:%S')
date=mydate.strftime("%W")
print(date)
Result:
38
I am new to python date and time types.
I have a date value.
date = '2018-11-10 10:55:31+00:00'
I need to check this date value is older than 90 days.
I tried :
from datetime import datetime
from datetime import timedelta
past = datetime.now() - timedelta(days=90)
date = '2018-11-10 10:55:31+00:00'
if past > date :
print("This is older than 90 days")
failing with the following error :
TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
This might be because the date format for 'past' and the date value which I passed is different.
How can I come up with this ?
You have to use strptime to convert a string into a date.
The comparaison operator only applies between datetime.
date = datetime.strptime('2018-11-10 10:55:31', '%Y-%m-%d %H:%M:%S')
then can you do
if past > date :
print("This is older than 90 days")
You can use dateutil package and just convert your date string date to `datetime object and then check the condition with :
from dateutil import parser
past = datetime.now() - timedelta(days=90)
new_date = parser.parse("2018-11-10 10:55:31+00:00")
if past > new_date :
print("This is older than 90 days")
that it : )
You need to convert your date string to datetime. You can do this in a couple of ways.
Use built-in datetime.strptime
For example, first convert to datetime before your comparison. This requires you to specify the format precisely ahead of time:
date = '2018-11-10 10:55:31+00:00'
date = datetime.strptime(date[:-6], '%Y-%m-%d %H:%M:%S')
print(date)
datetime.datetime(2018, 11, 10, 10, 55, 31)
Use a 3rd party library
One popular tool is dateutil.parser, which is able to parse most common datetime formats without the format specified in advance:
from datetime import datetime, timedelta
from dateutil import parser
past = datetime.now() - timedelta(days=90)
date1 = '2018-11-10 10:55:31+00:00'
date2 = '2017-11-10 10:55:31+00:00'
for date in (date1, date2):
if past > parser.parse(date[:-6]):
print(f'This is older than 90 days: {date}')
This is older than 90 days: 2017-11-10 10:55:31+00:00
I'm making a calculator which tells you how many days there is between today and the given date. The dates is imported from a file and is written in format yyyy/mm/dd and dd/mm/yyyy.
I have two problems:
1: The format which the dates are written in varies. A few of the dates is written in reverse. How do I reverse them? I get ValueError: day is out of range for month.
2: When I try to subtract "today" with the "dates" I get the error TypeError: unsupported operand type(s) for -: 'str' and 'str' and when I add "int" I get ValueError: invalid literal for int() with base 10: '2015, 10, 23'
Any advice? :)
for line in response:
line = (line.decode(encoding).strip())
year, month, day = line.split('/')
today = date.today().strftime("%Y, %m, %d")
dates = datetime(int(year), int(month), int(day)).strftime("%Y, %m, %d")
print(int(today)-int(dates))
No need to convert into integer if you have two date objects, you can just subtract one from the other and query the resulting timedelta object for the number of days:
>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7
And it works with datetimes too — I think it rounds down to the nearest day:
>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6
Your second problem is caused by calling strftime too early. date objects can be evaluated to each other, but strings cannot. ie
today = date.today()
dates = date(int(year), int(month), int(day))
print((today-dates).days)
also, you should use date objects for both.
You're second problem can be fixed with some simple error checking like
if year < day:
switch(year,day) #pseudo code
or something more verbose than that but you get the idea.
EDIT:
I forgot that comparisons return a timedelta object. these objects only hold days and smaller time sequences (hours, mins, seconds etc)