I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go
Related
ask the user enter the date in the format YYYY-MM-DD
1.what age of user in days;
2.what day of week (in German language) was the birth.
import datetime
b = int(input('Enter your birthdate: '))
bb = datetime(b, '%Y-%m-%d')
a = datetime.date.today()
c = a-bb
print(c)
from datetime import datetime
d = input("Enter the date of birth: ")
print(d.strftime('%A'))
Your problem is trying to convert an input that's probably in YYYY-MM-DD format, into an int. This will not work in Python. Simply leave as a string and convert to a date.
Use setlocale to choose German for output.
from datetime import datetime
from datetime import date
# set language output to German
import locale
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
# convert a str to a date, subtract with current date to get # of days
date_time_str = input('Enter your birthdate: ')
bday = datetime.strptime(date_time_str, '%Y-%m-%d').date()
today = date.today()
print(today - bday)
# reuse the "bday" variable defined above, get day of week (in German)
print(bday.strftime('%A'))
Output:
730 days, 0:00:00
Mittwoch
I have a date object like
Date = '202011'
This is yyyymm format.
I want to get the same month but n years prior. For example if n = 2, then I should get '201811'
Is there any function available to achieve this?
You can use the datetime module and dateutil library for this:
import datetime
from dateutil.relativedelta import relativedelta
fmt = '%Y%m'
date_string = '202011'
n = 2
# Parse `date_string` into a date object.
date = datetime.datetime.strptime(date_string, fmt).date()
# 2020-11-01
# Subtract `n` years.
new_date = date + relativedelta(years=-n)
# Output in the same format.
print(new_date.strftime(fmt)) # -> 201811
Related questions:
Python date string to date object
How do I calculate the date six months from the current date using the datetime Python module?
Just parse it into a Python datetime object and use its replace() method.
from datetime import datetime
years_ago = 2
date = datetime.strptime('202011','%Y%m')
date = date.replace(year=date.year-years_ago)
# This is the modified date object
print(date)
# Formatted back in your format
print(date.strftime('%Y%m'))
This solution does not require any external dependency
Here's a similar solution to the others, but only using the standard library, and as a function.
def subtract_years(date_string: str, diff: int) -> str:
dt = datetime.strptime(date_string, "%Y%m")
new_dt = dt.replace(year=dt.year - diff)
return new_dt.strftime("%Y%m")
# ❯ subtract_years("202011", 2)
# '201811'
I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
Prepend the century to your date using your own pivot:
year = int(date[0:2])
if 59 <= year <= 99:
date = '19' + date
else
date = '20' + date
and then use strptime with the %Y directive instead of %y.
import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
dt = dt.replace( year=dt.year-100 )
^2053 ^1953
print dt.strftime( '%Y-%m-%d' )
You can also perform the following:
today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]
Recently had a similar case, ended up with this basic calculation and logic:
pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100
def year_2to4_digit(year):
return century + year if century + year > pivotyear else (century + 100) + year
If you are dealing with very recent dates as well as very old dates and want to use the current date as a pivot (not just the current year), try this code:
import datetime
def parse_date(date_str):
parsed = datetime.datetime.strptime(date_str,'%y%m%d')
current_date = datetime.datetime.now()
if parsed > current_date:
parsed = parsed.replace(year=parsed.year - 100)
return parsed
I'm quite lost and I'm in need of trying to format some code so it ends up having dashes in the date. I can get 3, 12, 28 but I can't get 3-12-28. I am a super new beginner so I'm quite lost at the moment.
year = 3
month = 12
day = 28
print(date)
Try
print("{0}-{1}-{2}".format(year,month,day))
You could use datetime to format the result
import datetime
year = 3
month = 12
day = 28
dt = (datetime.date(year, month, day))
print(dt)
the result will be 0003-12-28
if you want more examples of datetime you could take a look at https://docs.python.org/2/library/datetime.html#
As you say you are new to python you can concatenate the strings together.
year = 3
month = 12
day = 28
date = year + "-" + month + "-" + day
print(date)
Alternatively you can use format to set the variables in your required format.
print(f"{year}-{month}-{day}")
Another method is to use datetime if you are using todays date
import datetime
today = datetime.date.today()
print(today)
I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
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)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)