Datetime to string conversion failed in Python - python

I written a CPython program in python 2.7 to find the no : of days between users birthday and current date.
I am able to achieve this when I trying to use date method but it fails when I try to use datetime method. When I am using the datetime method the current date is coming with time and If try to subract the user birth date it is giving error.
So I tried to get the substring of datetime output (Eg :x = currentDate.strftime('%m/%d/%Y')) pass it to an variable and later convert into date (Eg: currentDate2 = datetime.strftime('x', date_format))but it failed.
Could you please help me understand why it is
from datetime import datetime
from datetime import date
currentDate3 = ''
currentDate = datetime.today()
currentDate1 = date.today()
currentDate3 = currentDate.strftime('%m/%d/%Y')
date_format = "%m/%d/%Y"
currentDate2 = datetime.strftime('currentDate3', date_format)
# The above line is giving error "descriptor 'strftime' requires a 'datetime.date' object but received a 'str'"
print(currentDate3)
print(currentDate1)
print(currentDate.minute)
print(currentDate)
userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
birthday = datetime.strptime(userInput, '%m/%d/%Y').date()
print(birthday)
days = currentDate1 - birthday
days = currentDate2 - birthday
print(days.days)

You are trying to format a string instead of a datetime:
currentDate2 = datetime.strftime('currentDate3', date_format)
Though, you don't need to format the current date into a string for this task - you need it to be datetime in order to calculate how many days are between it and a user entered date string, which you are loading with .strptime() into datetime.
Working sample:
from datetime import datetime
currentDate = datetime.now()
userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
birthday = datetime.strptime(userInput, '%m/%d/%Y')
days = (currentDate - birthday).days
print(days)

Related

Python datetime isoformat - count days until bithday from string - convert into datetime.datetime object

I want to count days until birthday. I have string with date of birth:
"1949-10-09T00:25:51.304Z"
and
tday = datetime.now().isoformat()
that returns
2020-08-05T21:02:31.532123
<class 'str'>
and I wonder how to create a delta time of this two strings.
I see the difference between those strings:
"1949-10-09T00:25:51.304Z" # date of birth
"2020-08-05T21:02:31.532123" # today
Do I have to change "today" string (slice to get:
"2020-08-05T21:02:31.532"
and then concatenate "Z" to get:
"2020-08-05T21:02:31.532Z"
and then convert this into object using datetime.strptime(),
and convert birthday date into an object date too, using this?
birthday = datetime.fromisoformat('1949-10-09T00:25:51.304Z')
Or there is a smarter way of doing that?
To get the birthday string I have to use that function that parse JSON file.
date=get_double_nested_table_data(0, "dob", "date")
birthday = datetime.fromisoformat(date)
now = datetime.now()
delta = now - birthday
It doesn't work.
I did that using answer below:
def get_days_until_birthday(index: int, first_table: str, second_table: str):
birthday_str = get_double_nested_table_data(index, first_table, second_table)
birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
now = datetime.now()
delta = now - birthday
return delta.days
and that returns rows like that:
weird ints
I changed that function into this:
def get_days_until_birthday(index: int, first_table: str, second_table: str):
now = datetime.now()
year = now.year
birthday_str = get_double_nested_table_data(index, first_table, second_table)
birthday_str = str(year) + birthday_str[4:]
birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
now = datetime.now()
delta = now - birthday
return delta.days
and that works fine only if birthday will come in this year. That function don't return correct days if birthday will be in the next year.
Could you know how to change that?
What you want is substracting the two datetimes which give you the timedelta between them
from datetime import datetime
birthday_str = '1949-10-09T00:25:51.304Z'
# you can remove the Z by slicing
birthday = datetime.fromisoformat(birthday_str[:-1])
# or with strptime
birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
now = datetime.now()
delta = now - birthday
# return the number of days (positive) there is between now and birthday date
return (now - birthday).days if birthday < now else (birthday - now).days
strptime format reference:
%Y is the year in 4 digits*
%m* the month in 2 digits
%d the day in 2 digits
T to still match the format of the string you're using
%H is the hour
: to still match the format of the string you're using
%M is the minutes
%S is for the seconds
. to still match the format of the string you're using
%f is for the microseconds
Z to still match the format of the string you're using

How to compare today's date and date stored in a string (without time)?

With python, How can I check if a date stored in a string has already passed?
My current code:
from datetime import date, datetime
date1 = date.today()
data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')
print(date1<=data2_obj)
The code above gives me the following error:
TypeError: can't compare datetime.datetime to datetime.date
Note that I would not want to work with any time - just the date (this case the treated in 32287708)
Use the .date() method to get the date component like this:
from datetime import date, datetime
date1 = date.today()
date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)
Output:
False

How to subtract from date given as user input?

So I'm trying to subtract one day from a users input of 2018-02-22 for example. Im a little bit stuck with line 5 - my friend who is is leaps and bounds ahead of me suggested I try this method for subtracting one day.
In my online lessons I haven't quite got to datetime yet so Im trying to ghetto it together by reading posts online but got a stuck with the error :
TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date()
new = date1.replace(day=date1.day-1, hour=1, minute=0, second=0, microsecond=0)
print (new)
So my aim is the get the out put 2018-02-21 if I put in 2018-02-22.
Any help would be amazing :)
First of all a timedeltais best used for the purpose of doing date arithmetcs. You import timedelta but don't use it.
day = timedelta(days=1)
newdate = input_datetime - day
Second problem is you're not initializing a date object properly. But in this case it would be better to use datetime as well as strptime to parse the datetime from the input string in a certain format.
date_entry = input('Enter a date in YYYY-MM-DD format')
input_date = datetime.strptime(date_entry, "%Y-%m-%d")
day = timedelta(days=1)
newdate = input_datetime - day
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
date1 = datetime.strptime(date_entry, '%Y-%m-%d')
print date1+timedelta(1)
Maybe you need something like this
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format ')
# convert date into datetime object
date1 = datetime.strptime(date_entry, "%Y-%m-%d")
new_date = date1 -timedelta(days=1) # subtract 1 day from date
# convert date into original string like format
new_date = datetime.strftime(new_date, "%Y-%m-%d")
print(new_date)
Output:
Enter a date in YYYY-MM-DD format 2017-01-01
'2016-12-31'

Can you do sums with a datetime in Python?

I know how to get the date:
from datetime import datetime
time = datetime.now()
print(time)
But is there a way where you can work out the days/hours until a certain date, maybe storing the date as an integer or something? Thx for all answers
Just create another datetime object and subtract which will give you a timedelta object.
from datetime import datetime
now = datetime.now()
then = datetime(2016,1,1,0,0,0)
diff = then - now
print(diff)
print(diff.total_seconds())
15 days, 3:42:21.408581
1309365.968044
If you want to take user input:
from datetime import datetime
while True:
inp = input("Enter date in format yyyy/mm/dd hh:mm:ss")
try:
then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S")
break
except ValueError:
print("Invalid input")
now = datetime.now()
diff = then - now
print(diff)
Demo:
$Enter date in format yyyy/mm/dd hh:mm:ss2016/01/01 00:00:00
15 days, 3:04:51.960110
I have taken your answer and developed it so that the user can enter the date that they want: Here it is
from datetime import datetime
year=int(input("What year?"))
month=int(input("What month?"))
day=int(input("What day?"))
hour=int(input("What hour?"))
minute=int(input("What minute?"))
second=int(input("What second?"))
then = datetime(year,month,day,hour,minute,second)
now = datetime.now()
diff = then - now
print(diff)
print(diff.total_seconds())
Thanks you all for your answers :D
Now Variable
Here is even better code, you can just take out the now variable, and put it directly in the difference integer
from datetime import datetime
while True:
inp = input("Enter date in format yyyy/mm/dd hh:mm:ss")
try:
then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S")
break
except ValueError:
print("Invalid input")
diff = then - datetime.now()
print(diff, "until", inp)
print(diff.total_seconds(),"seconds")

Need Assistance with This Simple Python Code

Here is my code & this is my error : AttributeError: type object 'datetime.datetime' has no attribute 'strptime
#Trying to calculate how many days until a project is due for
import datetime
project = input('When is your project due for Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/Y').date()
days = project - deadline
print(days)
print(days.days)
Thank You in advance #KOH
Looks like you need something like this:
import datetime
project = input('When is your project due for. Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/%Y').date()
delta = deadline - datetime.datetime.now().date()
print(delta.days)
Using Python3 there is no errors with datetime:
>>> datetime.datetime.strptime("08/11/2015", "%m/%d/%Y").date()
datetime.date(2015, 8, 11)
I'm not sure why you were getting that AttributeError, but I guess we resolved it in the comments. You were also getting an error because your formatting string was missing a %. And once you fix that, you would get an error saying you can't subtract a date from a str.
Even with all the errors fixed, what the code is doing isn't what you're trying to do. It looks like you're trying to subtract the user-provided date from itself, but I'm guessing you want to subtract today's date from the user-provided date, in order to get the number of days until the user-provided date.
Here's the fixed code, with some formatting and other changes thrown in.
from datetime import datetime
deadline_str = input('When is your project due? Specify mm/dd/yyyy: ')
deadline = datetime.strptime(deadline_str, '%m/%d/%Y').date()
days_till_deadline = (deadline - datetime.today().date()).days
print("{0} days till the project is due.".format(days_till_deadline))
So this is the code written by me and it works...
#todays date programme
import datetime
currentDate = datetime.date.today()
#currentDate is date which is converted to string with variable current in the format dd/mm/yyyy
current = datetime.datetime.strftime(currentDate, '%d/%m/%Y')
#input statements
userInput = input('Please enter your project deadline (dd/mm/yyyy)\n')
print()
##prints...
print("Today's Date is "+current)
print()
print("Your project deadline is " + userInput)
#userInput is a string which is converted to date with variable Input
Input = datetime.datetime.strptime(userInput, "%d/%m/%Y").date()
##Calculating remaining days
remainingDays = Input - currentDate
remainingDays = remainingDays.days
print()
print('The days remaining for deadline are '+str(remainingDays)+' days')
I guess it's something like this.
Because here we had to import the date time first cos we working with the date.
Then we had to get the current date in order to be able to get the project deadline.
import datetime
current_date = datetime.datetime.now()
user = input('Enter the days left for your project: ')
deadline = datetime.datetime.strptime(user, '%d%m%Y').date()
days_left = deadline - current_date.date()
print(days_left.days)

Categories

Resources