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
Related
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
My project involves reading CSV files concering city data and then computing various statistics. I am trying to create a function that will take city data from a CSV and the create a copy of the data except with a date filter applied. The user is prompted to enter a starting and ending date.
I am currently just testing and trying to get the data to print with the correct date filters applied. My biggest problem so far is that I can't seem to convert the strings entered by the user into a datetime format. Is there a way for the user to directly enter the data in datetime format?
def date_filtering(city_file):
date1 = input('Please enter a valid start date that you wish to explore?\n'
date2 = input('Please enter a valid end date.')
print(city_file.loc[date1:date2])
Thanks in advance!
I am working of the assumption you only need date, because you make no mention of time in the code. What you need to do is parse the input somehow to get the year, month, and day. I am sure it could be done using regex, but it is simpler to do it just with python builtins.
A normal way of representing date in the US is mm/dd/yyyy, so I will use that.
def strtodatetime(str):
month, day, year = [int(d) for d in str.split("/")]
return datetime.date(year, month, day)
date1 = strtodatetime(input('Please enter a valid start date that you wish to explore?\n'))
date2 = strtodatetime(input('Please enter a valid end date.'))
The strtodatetime splits the input string by the "/" character, then casts each element in the resultant list to integers. Then it returns a new datetime.date object with the corresponding dates.
If you are worried about the user inputting something of the wrong format, you can use a try block to make sure they don't. There are three possible sources of exceptions I can see, the user can input too many or too few /'s (like 10/2/1999/2), the user can input a date that doesn't exist (like 13/32/-1), or the user can input something that can't be cast to an int (like March/22/1999). All three raise ValueErrors, so that is the only exception we need to catch here. To catch that, we would change our code to
def strtodatetime(str):
month, day, year = [int(d) for d in str.split("/")]
return datetime.date(year, month, day)
date_filtering(city_file):
try:
date1 = strtodatetime(input('Please enter a valid start date that you wish to explore?\n'))
date2 = strtodatetime(input('Please enter a valid end date.'))
except ValueError:
print('Please enter a valid date in the format mm/dd/yyyy')
return date_filtering(city_file)
return city_file.loc[date1:date2]
print(data_filtering(city_file))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
import math
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY') #Prompts user to input
while repeat:
date_month = date[0:2] #Takes the input's month and keeps its value for the varible date_month
date_day = date[3:5] #Takes the input's day and keeps its value for the varible date_day
date_year = date[6:10] #Takes the input's year and keeps its value for the varible date_year
if 00 < int(date_month) < 13:
if 00 < int(date_day) < 32:
if 0000 < int(date_year) < 2017:
date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
else:
date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')
Roll-your-own parser code is silly. Python has batteries included for this:
import datetime
repeat = True
datestr = raw_input('Enter a date in the format MM/DD/YYYY')
while repeat:
try:
# Parse to datetime, then convert to date since that's all you use
date = datetime.datetime.strptime(datestr, '%m/%d/%Y').date()
except ValueError:
pass # Handle bad dates in common code
else:
if 0 < date.year < 2017:
datestr = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
continue # Bypass invalid date input common code
# Both exception and invalid years will fall through to this common code
datestr = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')
Obviously, as written, this doesn't actually terminate the loop under any conditions, but neither does your original code. The advantage here is that strptime does the heavy lifting; it validates many more things that your original code, through a single try/except, and handles tricky stuff like days of the month by month without special checks. You can access the year, month and day attributes of the date object it parses as before, as Python native ints, no individual int conversions as you go.
Note that if you wanted to use locale appropriate date representations, the format you chose happens to exactly match for en_US locale, and you could make it more portable to non-U.S. users by just using datetime.datetime.strptime(datestr, '%x') (though you'd have to make the raw_input prompt dynamic to match); that works the same as '%m/%d/%Y' for en_US, but switches ordering and separators for, say, a German locale, which would make it equivalent to '%d.%m.%Y'.
It is as simple as this:
>>> import calendar
>>> print(calendar.isleap(1999))
False
>>> print(calendar.isleap(2004))
True
There a more problems with the question than just if the year is leap or not. #Dex'ter solution will indeed tell you if year is leap or not, but thing is you can't really ask for that in the end. So your first question should be is the user input date a leap year:
if calendar.isleap(date_year):
, followed by month for which your code is functional. And than you)ll have another problem in the day.
if 00 < int(date_day) < 32:
This will give you erroneous results no matter if the year is leap or not because there are plenty of months than don't have 31 days. For that I would advise:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
EDIT: and by the way this last function supports leap year as well.
I rewrite your program.I wish it will help
import math
from datetime import datetime
repeat = True
date = raw_input('Enter a date in the format MM/DD/YYYY :')
while repeat:
try:
datetime.strptime(date, "%m/%d/%Y")
date = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY :')
except ValueError:
date = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY :')
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)
For reference, my timezone is Eastern - New York.
I am inserting events from a PostgreSQL database to a Google Calendar. I have been using UTC-4 since early June, when I finally got my app moved from v2 to v3, and for a couple of years in v2. Up until the August 18 that has worked giving me the correct time. On August 18 the time was off by one hour so I changed the setting to UTC-5. That worked for about 2 hours and then I have had to reset it back to UTC-4.
Now today, August 21, it is off an hour again and I have set the UTC back to -5. The events are getting inserted as they should with the exception of an event being an hour off and the UTC needing to be changed sometimes. The system time is correct on my server.
Any ideas on what is happening?
Some of my code snippets:
#get an event from a PostgreSQL database to insert into a Google Calendar
curs.execute("SELECT c_event_title,c_name,c_event_date,c_event_starttime,c_event_endtime,c_department,seat_arrange,c_attendee_count from sched_421 where sched_id_421=%i;" %recnum)
mit=curs.fetchall() # mit IS NOW ALL THE RESULTS OF THE QUERY
for myrec in mit: # FOR THE ONE RECORD (EVENT) IN THE QUERY RESULTS
myend_time = time.strftime("%I:%M %p", time.strptime(str(myrec[4]),"%H:%M:%S"))
if myend_time[0]=='0': # Remove leading zero for 01:00 - 09:00
myend_time = myend_time[1:]
title = ' - %s %s - Group:%s' %(myend_time,myrec[0],myrec[5])
mycontent = myrec[0]+' - '+ myrec[5]
content = mycontent
where = where_dict[room_calendar]
# THIS IS WHERE THE UTC IS, SOMETIMES 4 WORKS SOMETIMES 5 WORKS
start_time = '%sT%s-05:00' %(myrec[2],myrec[3]) # Google format
end_time = '%sT%s-05:00' %(myrec[2],myrec[4]) # Google format
myend_time = '%s' %myrec[4] # User format (am/pm)
seat_arrange = '\nSeating - %s' %str(myrec[6])
attendee_count = '\nNumber of participants: %s' %str(myrec[7])
descript = str(myrec[0]) + ' ' + seat_arrange + attendee_count+ "\n Created By: me#somewhere.com"
# upload the event to the calendar
created_event = service.events().insert(calendarId=calendar_dict[room_calendar], body=event).execute()
Are the dates you are looking at on different sides of the daylight savings switch?
Eastern Time Zone is UTC-4:00 from March to November and UTC-5:00 from November to March.
Hard-coding the TZ Offset like that is a bad idea, especially in a TZ that uses daylight savings. It would be best to store all the times as UTC and just apply the TZ information at the endpoints (data input and data display).
At the very least, you will want to have something calculate the correct TZ offset, based on the date, like a helper function or some block of logic.
I'm not sure how much control you have over the data in the database, so that would dictate which path you choose.
Ideally, you could change the 3 fields (date, start time, end time) in the database into 2 (start datetime UTC, end datetime UTC)
I have had to change this code:
# THIS IS WHERE THE UTC IS, SOMETIMES 4 WORKS SOMETIMES 5 WORKS
start_time = '%sT%s-05:00' %(myrec[2],myrec[3]) # Google format
end_time = '%sT%s-05:00' %(myrec[2],myrec[4]) # Google format
to (check to see if the event is in daylight savings time or not, this was not necessary with v2)
if bool (pytz.timezone('America/New_York').dst(datetime.datetime(myrec[2].year,myrec[2].month,myrec[2].day), is_dst=None)):
utc_offset = '4'
else:
utc_offset = '5'
start_time = '%sT%s-0%s:00' %(myrec[2],myrec[3],utc_offset)
end_time = '%sT%s-0%s:00' %(myrec[2],myrec[4],utc_offset)