getting 2 different date input from user - python

I am trying to get user input for 2 different dates which i will pass on to another function.
def twodifferentdates():
print("Data between 2 different dates")
start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m&d&Y')
end_date = datetime.strptime(input('Enter end date in m/d/y format'), '%m&d&Y')
print(start_date)
twodifferentdates()
I have tried a lot of different ways to enter the dates but i keep getting
ValueError: time data '01/11/1987' does not match format '%m&d&Y'
I have used the same code which was discussed in:
how do I take input in the date time format?
Any help here would be appreciated.

Replace %m&d&Y with %m/%d/%Y as described in the referenced post.

datetime.strptime() requires you to specify the format, on a character-by-character basis, of the date you want to input. For the string '01/11/1987' you'd do
datetime.strptime(..., '%m/%d/%Y')
where %m is "two-digit month", %d is "two-digit day" and %Y is "four-digit year" (as opposed to two-digit year %y. These values are separated by slashes.
See also the datetime documentation which describes how to use strptime and strftime.

I'm not very experienced with the datetime module, but the error seems to be the way you're taking input. You should be taking it like this:
start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m &d &Y')
or
start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m/&d/&Y')

Related

Convert Shell date format to Python date format

Can below piece of shell date format be converted to python date format?
date_used = $(date --date="$(date +%Y-%m-15) - 1 month" "+%Y_%m")
As per my understanding this above format is just taking day as 15 of current month and it simply subtracts 1 month and results in giving output in the format of year_month.
Output of the above shell date format -->
echo $date_used = 2022_05
Can this particular scenario be done using python?
Any update about it would be really appreciable.
An equivalent would be:
from datetime import datetime,timedelta
# Current date, replace date with 15, subtract 30 days and format
date_used = (datetime.now().replace(day=15) - timedelta(days=30)).strftime('%Y_%m')
print(date_used)
Output:
2022_05
You can use python's datetime module to do this
it has a function named strptime you can use to read date and time data with format code very similar to unix date format (or maybe its even same i'm not sure)
and strftime to output in a certain format as well
you can see the functions and the format code to see if there's any different on
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
Example code
from datetime import datetime, timedelta
date = datetime.strptime((datetime.now() - timedelta(days=30)).strftime("%Y-%m") + "-15", "%Y-%m-%d")
print(date)
print(date.strftime("%Y_%m"))
output
2022-05-15 00:00:00
2022_05

I have a list of dates and I want to subtract actual date from each of them to know how many day passed. Is there any fast way to do this?

I know I should import datetime to have actual date. But the rest is black magic for me right now.
ex.
dates = ['2019-010-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = datetime.datetime.now()
How can I subtract this and as a result have new list with days that passed by from dates to actual_date?
If I'm understanding correctly, you need to find the current date, and then find the number of days between the current date and the dates in your list?
If so, you could try this:
from datetime import datetime, date
dates = ['2019-10-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = date.today()
days = []
for date in dates:
date_object = datetime.strptime(date, '%Y-%m-%d').date()
days_difference = (actual_date - date_object).days
days.append(days_difference)
print(days)
What I am doing here is:
Converting the individual date strings to a "date" object
Subtracting the this date from the actual date. This gets you the time as well, so to strip that out we add .days.
Save the outcome to a list, although of course you could do whatever you wanted with the output.

Date formatting to month

I want to change the format of "Date" column from 10/15/2019 to m/d/y format.
tax['AsOfdate']= pd.to_datetime(tax['date'])
How do I do it?
like this, and here is the documentation.
tax['AsOfdate']= pd.to_datetime(tax['date'], format="%m/%d/%Y" )
Here is an example with today's date formatting:
from datetime import date
today = date.today()
new_format = today.strftime("%m/%d/%y")
print(today, new_format)
Pandas to_datetime function accepts a format command which accepts strftime notation.
Pandas docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
Strftime docs: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
m/d/y notation would be:
tax['AsOfdate']= pd.to_datetime(tax['date'], format='%m/%d/%y)
Assuming you want everything zero padded with two digits like 01/01/19 for January first 2019. If you need something else, the strftime formatting link shows all the codes that let you choose padding or not, four-digit year or two-digit, and so on.

How to format date to 1900's?

I'm preprocessing data and one column represents dates such as '6/1/51'
I'm trying to convert the string to a date object and so far what I have is:
date = row[2].strip()
format = "%m/%d/%y"
datetime_object = datetime.strptime(date, format)
date_object = datetime_object.date()
print(date_object)
print(type(date_object))
The problem I'm facing is changing 2051 to 1951.
I tried writing
format = "%m/%d/19%y"
But it gives me a ValueError.
ValueError: time data '6/1/51' does not match format '%m/%d/19%y'
I couldn't easily find the answer online so I'm asking here. Can anyone please help me with this?
Thanks.
Parse the date without the century using '%m/%d/%y', then:
year_1900 = datetime_object.year - 100
datetime_object = datetime_object.replace(year=year_1900)
You should put conditionals around that so you only do it on dates that are actually in the 1900's, for example anything later than today.

Difficulty with the replace method

I must have the user enter a date in mm/dd/yy format and then output the string in long-date format like January, ##, ####. I cannot for the life of me get the month to replace as a the word.
def main():
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
validate(month, day, year)#validates input
get_month(get_date)
def validate(month,day,year):
while month>12 or month<1 or day>31 or day<1 or year!=15:
print("if you would like to enter a one-digit number, enter a zero first, then the number\n theres only 12 months in a year\n only up to 31 days in a month, and\n you must enter 15 as the year")
get_date=input('Input a date in mm/dd/yy format!:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
def get_month(get_date):
if get_date.startswith('01'):
get_date.replace('01','January')
print(get_date)
I have tried a plethora of things to fix this but I cannot make January appear instead of 01.
Strings in Python are immutable, they don't change once they're created. That means any function that modifies it must return a new string. You need to capture that new value.
get_date = get_date.replace('01','January')
You can do this (and simplify the code) using python's date module.
The strptime function will parse a date from a string using format codes. If it's can't parse it correctly, it will raise a value error, so no need for your custom validation function
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strptime
The strftime function will print out that date formatted according to the same codes.
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strftime
Updated, your code would look something like this:
from datetime import datetime
parsed = None
while not parsed:
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
try:
parsed = datetime.strptime(get_date, '%m/%d/%y')
except ValueError:
parsed = None
print parsed.strftime('%B %d, %Y')
Why don't you use datetime module ?
year = 2007; month=11; day=3
import datetime
d = datetime.date(year, month, day)
print d.strftime("%d %B %Y")
You might be better off using Python's datetime module for this:
from datetime import datetime
entered_date = input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
d = datetime.strptime(entered_date, '%m/%d/%y')
entered_date = d.strftime('%B, %d, %Y')
e.g.
'February, 29, 2016'
This way you catch invalid dates (such as 02/29/15) as well as badly-formatted ones.

Categories

Resources