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)
Related
I am new to functions and I am trying to write a function that returns the number of days between two dates:
My attempt:
import datetime
from dateutil.parser import parse
def get_x_days_ago (date_from, current_date = None):
td = current_date - parse(date_from)
if current_date is None:
current_date = datetime.datetime.today()
else:
current_date = datetime.datetime.strptime(date_from, "%Y-%m-%d")
return td.days
print(get_x_days_ago(date_from="2021-04-10", current_date="2021-04-11"))
Expected outcome in days:
1
So there seem to be multiple issues, and as I said in the comments, a good idea would be to separate the parsing and the logic.
def get_x_days_ago(date_from, current_date = None):
if current_date is None:
current_date = datetime.datetime.today()
return (current_date - date_from).days
# Some other code, depending on where you are getting the dates from.
# Using the correct data types as the input to the get_x_days_ago (datetime.date in this case) will avoid
# polluting the actual logic with the parsing/formatting.
# If it's a web framework, convert to dates in the View, if it's CLI, convert in the CLI handling code
date_from = parse('April 11th 2020')
date_to = None # or parse('April 10th 2020')
days = get_x_days_ago(date_from, date_to)
print(days)
The error you get is from this line (as you should see in the traceback)
td = current_date - parse(date_from)
Since current_date="2021-04-11" (string), but date_from is parsed parse(date_from), you are trying to subtract date from the str.
P.S. If you have neither web nor cli, you can put this parsing code into def main, or any other point in code where you first get the initial strings representing the dates.
It looks like you're already aware that you can subtract a datetime from a datetime. I think, perhaps, you're really looking for this:
https://stackoverflow.com/a/23581184/2649560
I just want to write a script for taking the date
as input from user, if user don't enter date then program should take system's date.
I tried the following code. How can I do this by using any if-else condition or any functions in Python.
date_entry = input('Enter a date in YYYY-MM-DD format:')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
How can I write this script for above problem?
It's best to use exception handling for this matter.
Use try and except to handle any exceptions thrown by datetime module whenever any input given is not according to the format wanted.
try:
date_entry = input('Enter a date in YYYY-MM-DD format:')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
except ValueError:
date1=datetime.date.today().strftime('%Y-%m-%d')
So I have the following input prompt:
start_date = input("What is the start date in format mm/dd/yyyy: ")
I want to make it so that if someone does not give an input in the proper format they are simply reprompted to do it again. Format is provided above, so something like January 20, 2020 being 01/20/2020, and the preceding 0 for January is important. I guess you'd also have to make sure they don't input impossible values like a 13th month of a 40th day of the month. I assume it would be something like:
while True:
start_date = input("What is the start date in format mm/dd/yyyy: ")
if ##properly formatted
break
The datetime module, through its datetime class, provides a very helpful method called strptime(), that it seems like what you need for your case. You can read more about it here
You could use it as follows:
while True:
try:
start_date = datetime.datetime.strptime(
input("What is the start date in format mm/dd/yyyy: "), "%m/%d/%Y"
)
except ValueError:
print("Invalid date")
else:
break
# You can keep using the start_date variable from now on
I have a program that runs a Windows "net user" command to get the expiration date of a user. For example: "net user justinb /domain"
The program grabs the expiration date. I am taking that expiration date and setting it as variable datd
In the example below, we'll pretend the expiration date given was 1/10/2018. (Note: Windows does not put a 0 in front of the month)
import time
datd = "1/10/2018"
# places a 0 in front of the month if only 1 digit received for month
d = datd.split("/")
if len(d[0])==1:
datd="0"+datd
print("Changed to: " + datd)
myDate = (time.strftime("%m/%d/%Y"))
print ("This is today's date: " + myDate)
if datd <= myDate: # if datd is is earlier than todays date
print (" Password expired. ")
else:
print (" Password not expired. ")
input(" Press Enter to exit.")
Right now, it gives me correct information if datd equals a date in 2017. I am getting a problem with the year 2018 and on though. It is telling me that 1/10/2018 comes before today's date of 10/24/2017.
Is there a way I change the format of the dates properly so that they are read correctly in this program?
I want the output to say that the "Password is not expired" if datd = 1/10/2018
from datetime import datetime
string_input_with_date = "25/10/2017"
past = datetime.strptime(string_input_with_date, "%d/%m/%Y")
present = datetime.now()
past.date() < present.date()
This should do the job for you! Both handling day in format with leading 0 and without it.
Use .date() to make comparision of datetimes just to extent of daily date.
Warning: if you would like to be 100% correct and purist take care about timezone related issues. Make sure what time zone is assumed in your windows domain etc.
Reference:
datetime strptime - https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
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)