I want my program to take user input in form of a date and the control if it is valid. But with the code I have know the program say that it is wrong regardless of what format i give. I don't see the problem with the code:
import datetime
def visit_date():
while True:
date_visit = input("Enter the date you want to visit the Zoo in YYYY-MM-DD format: ")
try:
return datetime.datetime.strptime(date_visit, "%d/%m/%y")
except ValueError:
print("Not a valid format\n")
You're asking the user for a date in the format YYYY-MM-DD but then trying to parse it according to this format %d/%m/%y.
You instead should parse the string in the same way that you requested it, %Y-%m-%d
You're looking for format %d/%m/%y and asking for %Y-%m-%d
> date_visit = '2016-11-23'
> datetime.datetime.strptime(date_visit, "%Y-%m-%d")
datetime.datetime(2016, 11, 23, 0, 0)
Some notes:
%Y : Year in four digits %y : year in two digits.
%d/%m/%y translates to "day of month in one or two digits, /, month of year in one or two digits, / year in two digits".
%Y-%m-%d translates to "four-digit-year, -, month-of-year, - day-of-month"
Your prompt asks you to enter in YYYY-MM-DD, but your strptime is attempting to use the format %d/%m/%y. You need to have the formats to match for strptime to work
import datetime
d = '2016-11-21'
d = datetime.datetime.strptime(d, "%Y-%m-%d")
d = datetime.datetime(2016, 11, 21, 0, 0)
>>> 2016-11-21 00:00:00
d = '11/21/2016'
d = datetime.datetime.strptime(d, "%d/%M/%Y")
d = datetime.datetime(2016, 11, 21, 0, 0)
>>> 2016-11-21 00:00:00
I personally like to use the python-dateutil module for parsing date strings that allows for different formats
pip install python-dateutil
from dateutil.parser import parse
d1 = 'Tuesday, October 21 2003, 12:14 CDT'
d2 = 'Dec. 23rd of 2012 at 12:34pm'
d3 = 'March 4th, 2016'
d4 = '2015-12-09'
print(parse(d1))
>>> 2003-10-21 12:14:00
print(parse(d2))
>>> 2012-12-23 12:34:00
print(parse(d3))
>>> 2016-03-04 00:00:00
print(parse(d4))
>>> 2015-12-09 00:00:00
Related
I have a list of dates from input like the ones below.
I am working on a project and only want to accept the dates that follow the format April 1, 1990 or the January 13, 2003 (taking in any month) format from user input, and any other date format I do not want to accept. I am struggling on how I would use the replace or find function to obtain these goals? Once I receive that format I want to print out the date in this format 7/19/22. If I have the dates in the right format I used the replace function to replace the space, and comma but how would I take that month and replace it with its numerical value? Sorry for all these questions I am just stuck and have been working on this for a while now.
April 1, 1990
November 2 1995
7/19/22
January 13, 2003
userinput = input("Please enter date")
parsed_date = userinput.replace(" ", "/", 2)
new_parsed_date = parsed_date.replace(',',"")
print(new_parsed_date)
March/1/2019 Here is my output when I parse the date. Is there also any easier way to do this task?
You should take a look at the strptime method of the Python datetime object.
Basically you would write code that looks like this:
>>> from datetime import datetime
>>> datetime.strptime("January 13, 2003", "%B %d, %Y")
datetime.datetime(2003, 1, 13, 0, 0)
Documentation for strptime: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
I can't really understand what you're going to do. You said that you only want to accept the certain dates formats from user input and ignore other dates formats.
April 1, 1990 # Accept
January 13, 2003 # Accept
November 2 1995 # Ignore (lack of comma)
7/19/22 # Ignore (use numerical value in month field)
May I just think that you would like to accept the format like January 13, 2003 and print or save them in the format 01/13/2003?
Then you should consider strptime() and strftime() methods for datetime object.
# get the date string from user input
date_input = input("Please Enter Date: ")
input_format = "%B %d, %Y"
output_format = "%m/%d/%Y"
try:
parsered_date = datetime.datetime.strptime(date_input, input_format)
.strftime(output_format)
print(parsered_date)
except ValueError:
print("This is the incorrect date string format.")
Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)
The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00
%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.
So I have the following string : " 01 January 2016" to UTC ISO date format ?
I'm using arrow module and the following code, but it's full of errors, and I was thinking that may be, there was a smaller more elegent solution as python encourages elegant and easier ways to do things, anyways here's my code :
updateStr = " 01 January 2016" #Note the space at the beginning
dateList = updateStr.split[' ']
dateDict = {"day" : dateList[1],"month": months.index(dateList[2])+1, "year" : dateList[3]}
dateStr = str(dateDict['day']) + "-" + str(dateDict["month"]) + "-" + str(dateDict["year"])
dateISO = arrow.get(dateStr, 'YYYY-MM-DD HH:mm:ss')
Please help me I have to convert it to the UTC ISO formats, Also months is a list of months in the year .
You can use datetime:
>>> updateStr = " 01 January 2016"
>>> import datetime as dt
>>> dt.datetime.strptime(updateStr, " %d %B %Y")
datetime.datetime(2016, 1, 1, 0, 0)
>>> _.isoformat()
'2016-01-01T00:00:00'
Keep in mind that is a 'naive' object without a timezone. Check out pytz to deal with timezones elegantly, or just add an appropriate utcoffset to the datetime object for UTC.
Using arrow:
>>> import arrow
>>> updateStr = " 01 January 2016"
>>> arrow.get(updateStr, "DD MMMM YYYY").isoformat()
'2016-01-01T00:00:00+00:00'
>>>
You can use datetime's methods to parse this date string and then reformat it to UTC format:
>>> from datetime import datetime
>>> updateStr = " 01 January 2016" #Note the space at the beginning
>>> d = datetime.strptime(updateStr, ' %d %B %Y') # Same space here
>>> s = datetime.isoformat(d)
>>> s
'2016-01-01T00:00:00'
Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,date2):
while date1 < date2:
if date1.weekday() == 0:
yield date1
date1 = date1 + timedelta(days=1)
and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.
You could just feed the data into time.asctime().
>>> import time
>>> week = 6
>>> year = 2014
>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))
>>> atime
'Mon Feb 10 00:00:00 2014'
EDIT:
To convert this to a datetime.date object:
>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()
datetime.date(2014, 2, 10)
All about strptime \ strftime:
https://docs.python.org/2/library/datetime.html
mytime.strftime('%U') #for W\C Monday
mytime.strftime('%W') #for W\C Sunday
Sorry wrong way around
from datetime import datetime
mytime=datetime.strptime('2012W6 MON'. '%YW%U %a')
Strptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string.
Enjoy
A simple function to get the Monday, given a date.
def get_monday(dte):
return dte - datetime.timedelta(days = dte.weekday())
Some sample output:
>>> get_monday(date1)
datetime.date(2013, 12, 30)
>>> get_monday(date2)
datetime.date(2014, 12, 29)
Call this function within your loop.
We can just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
To piggyback and give a different version of the answer #anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like "11-2023":
import time
from datetime import datetime
def get_date_from_week_number(str_value):
temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))
return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()
In Sweden we sometimes use a strange date format, for example New Year is the 31/12. If I have this format as a string ,which can be any date between 1/1 and 31/12, and if we assume that it is this year, how do I get into a standard date format using Python (format as 2012-01-01 and 2012-12-31) that can be sore in be stored as a date in a mySQL database.
Simply split the two values, map them to integers and update a datetime.date() instance:
import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)
By using datetime.date.today() we get the current year.
Demo:
>>> import datetime
>>> somevalue = '31/12'
>>> day, month = map(int, somevalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 12, 31)
>>> someothervalue = '1/1'
>>> day, month = map(int, someothervalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 1, 1)
Alternatively, you could use the datetime.strptime() method to parse these dates, but you'll have to manually correct the year afterwards (it'll use 1900 as the default if no year is being parsed):
adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)
There is nothing strange about this format :)
You can use the datetime module:
import datetime
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012)
print d
>> datetime.date(2012, 12, 31)