Python 3.2 input date function - python

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)

Related

How to take a date from the user?

How would I go about designing a Python program which takes in a date from the user, a date that looks like this 3/13/17, and turns it into a date which looks like this 2017.3.13?
You can split the string by using the str.split method like this:
s = "3/13/17"
month, day, year = s.split("/")
print(f"20{year}.{month}.{day}")
Python will automatically assign the splitted values to the variables month, day, and year
Get the date as text and then convert it to date with the format you would like. or get the date as a number (month, date and year ) separately and make it as a date.
Example:
my_string = str(input('Enter date(yyyy-mm-dd): '))
my_date = datetime.strptime(my_string, "%Y-%m-%d")

Python: use datetime and ephem to get date only (without time)

I'm pretty new to python and I'm currently trying to write a code for a small project. My problem is that when I execute my code I get the date + time and I'm only interested in the date. I've tried googling the problem but haven't found a solution for using datetime and ephem together (I have to use ep.date(datetime(year, month, day)) so I can use the input date with other dates that I get from ephem).
This is a small example code of what I'm doing:
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
datetime(int(year), int(month), int(day))
new_date = ep.date(datetime(year, month, day))
print(new_date)
And this is my output:
https://i.stack.imgur.com/0VJQM.png
If you click on the link you'll see that I get 2020/2/2 00:00:00 for the input 2020-2-2, it doesn't make my code stop working, but because I'll display this date quite often, I'd like to remove the time and only have the date.
If you just need to display the date and don't need further calculations, you can convert the ephem Date type back into a Python datetime type, then convert the Python datetime into a date.
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
ephem_date = ep.date(datetime(year, month, day))
python_date_only = new_date.datetime().date()
print(python_date_only)
You can use ‘from datetime import date’ instead of ‘datetime’

Equivalent function of MatLab's "dateshift(...)" in Python?

MatLab can take a date and move it to the end of the month, quarter, etc. using the dateshift(...) function.
Is there an equivalent function in Python?
I'm not sure if it counts as the same, but the datetime module can make times available as a timetuple, with separate components for year, month, day etc. This is easy to manipulate directly to advance to the next month, etc.
If you don't mind using an extension, check out dateutil. The list of features starts with:
Computing of relative deltas (next month, next year, next monday, last week of month, etc);
The documentation for dateutil.relativedelta shows how to advance to various points.
I think calendar.monthrange should do it for you, e.g.:
>>> import datetime, calendar
>>> year = int(input("Enter year: "))
Enter year: 2012
>>> month = int(input("Enter month: "))
Enter month: 3
>>> endOfMonthDate = datetime.date(year, month, calendar.monthrange(year, month)[1])
>>> endOfMonthDate
datetime.date(2012, 3, 31)
>>>
You might find other helpful functions here: https://docs.python.org/2/library/calendar.html and here: https://docs.python.org/2/library/datetime.html

Compute number of dates between two string dates and return an integer

I have a .txt file data-set like this with the date column of interest:
1181206,3560076,2,01/03/2010,46,45,M,F
2754630,2831844,1,03/03/2010,56,50,M,F
3701022,3536017,1,04/03/2010,40,38,M,F
3786132,3776706,2,22/03/2010,54,48,M,F
1430789,3723506,1,04/05/2010,55,43,F,M
2824581,3091019,2,23/06/2010,59,58,M,F
4797641,4766769,1,04/08/2010,53,49,M,F
I want to work out the number of days between each date and 01/03/2010 and replace the date with the days offset {0, 2, 3, 21...} yielding an output like this:
1181206,3560076,2,0,46,45,M,F
2754630,2831844,1,2,56,50,M,F
3701022,3536017,1,3,40,38,M,F
3786132,3776706,2,21,54,48,M,F
1430789,3723506,1,64,55,43,F,M
2824581,3091019,2,114,59,58,M,F
4797641,4766769,1,156,53,49,M,F
I've been trying for ages and its getting really frustrating. I've tried converting to datetime using the datetime.datetime.strptime( '01/03/2010', "%d/%m/%Y").date() method and then subtracting the two dates but it gives me an output of e.g. '3 days, 0:00:00' but I can't seem to get an output of only the number!
The difference between two dates is a timedelta. Any timedelta instance has days attribute that is an integer value you want.
This is fairly simple. Using the code you gave:
date1 = datetime.datetime.strptime('01/03/2010', '%d/%m/%Y').date()
date2 = datetime.datetime.strptime('04/03/2010', '%d/%m/%Y').date()
You get two datetime objects.
(date2-date1)
will give you the time delta. The mistake you're making is to convert that timedelta to a string. timedelta objects have a days attribute. Therefore, you can get the number of days using it:
(date2-date1).days
This generates the desired output.
Using your input (a bit verbose...)
#!/usr/bin/env python
import datetime
with open('input') as fd:
d_first = datetime.date(2010, 03, 01)
for line in fd:
date=line.split(',')[3]
day, month, year= date.split(r'/')
d = datetime.date(int(year), int(month), int(day))
diff=d - d_first
print diff.days
Gives
0
2
3
21
64
114
156
Have a look at pleac, a lot of date-example there using python.

Python: Adding 3 weeks to any date

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

Categories