How to take a date from the user? - python

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")

Related

How to increase timestamp string to timestamp with new year, month, day Python datetime?

I want to write a function that takes in a string representing timestamp, then change the year, month and day of that timestamp but not the actual time. Then I want to return the resulting timestamp as a string. I'm having some trouble with the conversion, since I think I need to convert in the following sequence: string -> timestamp -> date -> timestamp -> string. I've read through the datetime library, but I'm having some trouble with this conversion. Any assistance, would be much appreciated!
Function inputs would look like this:
def change_date(string: timestamp, string: new_date)
#timestamp: string formatted like 1601403951777
#new_date: string formatted like YYYY-MM-DD
For instance timestamp 1601403951777 is Tuesday, September 29, 2020.
Try this,
from datetime import datetime
def change_date(dt):
#timestamp: string
#new_date: string formatted like YYYY-MM-DD
d= datetime.fromisoformat(dt)
new_date = d.strftime(('%Y-%m-%d'))
print(new_date)
dt = str(datetime.now())
print(dt)
change_date(dt)
output
2021-06-09 16:15:58.421486
2021-06-09
I would recommend using the .replace method of datetime objects:
def change_date(string: timestamp, string: new_date):
source_dt = datetime.fromtimestamp(int(timestamp))
year, month, date = [int(i) for i in new_date.split('-')]
return f"{source_dt.replace(year=year, month=month, date=date):...}"
where {:...} is the format you need.

How can I take list of Dates from csv (as strings) and return only the dates/data between a start date and end date?

I have a csv file with dates in format M/D/YYYY from 1948 to 2017. I'm able to plot other columns/lists associated with each date by list index. I want to be able to ask the user for a start date, and an end date, then return/plot the data from only within that period.
Problem is, reading dates in from the csv, they are strings so I cannot use if date[x] >= startDate && date[x] <= endDate because theres no way for me to turn dates in this format to integers.
Here is my csv file
I am already able to read in the dates from the csv to its own list.
How can I take the dates in my list and only return the ones within the user specified date range?
Here is my function for plotting the entire dataset right now:
#CSV Plotting function
def CSV_Plot (data,header,column1,column2):
#pyplot.plot([item[column1] for item in data] , [item[column2] for item in data])
pyplot.scatter([item[column1] for item in data] , [item[column2] for item in data])
pyplot.xlabel(header[column1])
pyplot.ylabel(header[column2])
pyplot.show()
return True
CSV_Plot(mycsvdata,data_header,dateIndex,rainIndex)
This is how I am asking the user to input the start and end dates:
#Ask user for start date in M/D/YYY format
startDate = input('Please provide the start date (M/D/YYYY) of the period for the data you would like to plot: ')
endDate = input('Please provide the end date (M/D/YYYY) of the period for the data you would like to plot: ')
You need to compare the dates.
I would suggest parsing the dates from your CSV into a datetime object, and also turning the user input value into a datetime object.
How to create a datetime object from a string? You need to specify the format string and the strptime() will parse it for you. Details here:
Converting string into datetime
In your case, it could be something like
from datetime import datetime
# Considering date is in M/D/YYYY format
datetime_object1 = datetime.strptime(date_string, "%m/%d/%Y")
Then you can compare them with a > or < operator. Here you can find details of how to compare the dates.

Django: Why Filtering By Year Works, But Not Month and Day?

I have a simple datetime field named date. Stores dates and time like this: 2015-07-04 01:40:00+00:00.
When I run
today = datetime.datetime.now().today()
x = game.objects.filter(date__year=today.year)
It works, however if i run
today = datetime.datetime.now().today()
x = game.objects.filter(date__month=today.month)
I get an empty list.
Current month is July. If you filter by the year part of the date being equal to current month, then you search for records being in the year of 07 AD. I believe you do not have such records. You need to filter by month of the date if you want to filter by month.

Python 3.2 input date function

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)

How to do groupby in pandas with part of date string?

Date Description
0 6/09/2012 Amazon
1 6/09/2012 iTunes
2 6/08/2012 iTunes
3 6/08/2012 Building
4 6/08/2012 Slicehost
I have a DataFrame like the above. I can pick out the day part of the above datestring using a function get_day() like this:
def get_day(date_string):
d = datetime.strptime(date_string, '%m/%d/%Y')
return d.day
Now how do I pass this function to the above DataFrame to get groupby going on the day rather than the datestring itself. Couldn't figure it out from looking at the docs. Any help appreciated.
df.groupby(get_day)
but I would convert the date strings to datetime objects first anyway.
Another problem is that you're calling .day which returns a day of month (number 1-31). You probably want to call .date():
def get_day(date_string):
return datetime.strptime(date_string, '%m/%d/%Y').date()
or directly
df.groupby(lambda x: datetime.strptime(date_string, '%m/%d/%Y').date())

Categories