I am creating a program which takes in fields for events, saves them to file and then loads & displays them on separate lines.

The 'date' field in my program should be in the format yyyy/mm/dd when it is entered. I have managed to implement this however my program still allows 1 number to be entered for the year when it should only allow 4 numbers for the year, 2 for the month and 2 for the day.

Please could someone show me how I could implement this in my program or how to improve the code I have, maybe by just entering the numbers e.g 20100315 rather than using the split with the commas.

import cPickle
 
def print_menu():
    print '1. Add an Event'
    print '2. Save Events to File'
    print '3. Load Events from File'
    print '4. Quit'
    print()
 
event_list = []
menu_choice = 0
print_menu()
start = 0
while True:
    menu_choice = input("Select Menu Item (1-4): ")
    if menu_choice == 1:
        try:
            print "Add Event"
            date = raw_input("Enter Date (yyyy,mm,dd): ")
            # Assuming that the user inputs this: yyyy,mm,dd
            date = date.split(',')
            if len(date[0]) == 2:
                date[0] = '20'+date[0]
            if len(date[1]) == 1:
                date[1] = '0'+date[1]
            if len(date[2]) == 1:
                date[2] = '0'+date[2]
            date = '/'.join(date)
            # if the format yyyy,mm,dd is not entered
        except IndexError:
            print "That was not in the format yyyy, mm, dd"
            start # restarts the loop
            continue
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)
    elif menu_choice == 2:
        filename = raw_input("Filename to save: ")
        pickle_file = open(filename, "w")
        cPickle.dump(event_list, pickle_file)
        pickle_file.close()
    elif menu_choice == 3:
        try:
            filename = raw_input("Filename to load: ")
            pickle_file = open(filename, "r")
            events = cPickle.load(pickle_file)    # events is a list of events
            pickle_file.close()
            for event in events:                  # print each member of events
                print "Events: %s" % '\t'.join(list(event))
        except IOError:
            print "No such file to load"
            start
            continue
    elif menu_choice == 4:
        break
    else:
        print_menu()
 
print "Goodbye"

This being the section containing the date:

if menu_choice == 1:
        try:
            print "Add Event"
            date = raw_input("Enter Date (yyyy,mm,dd): ")
            # Assuming that the user inputs this: yyyy,mm,dd
            date = date.split(',')
            if len(date[0]) == 2:
                date[0] = '20'+date[0]
            if len(date[1]) == 1:
                date[1] = '0'+date[1]
            if len(date[2]) == 1:
                date[2] = '0'+date[2]
            date = '/'.join(date)
            # if the format yyyy,mm,dd is not entered
        except IndexError:
            print "That was not in the format yyyy, mm, dd"
            start # restarts the loop
            continue
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)

Any help would be greatly appreciated. Thank You

Recommended Answers

All 8 Replies

From your code it appears, that you want to allow the following formats:
yyyy,mm,dd
yy,mm,dd -> 20yy,mm,dd
yyyy,m,d-> yyyy,0m,0d

You either allow only strict format or face the consequences...

import datetime
def event():
    ''' ask user a date and returns it in a yyyy/mm/dd format
        User input format: year,month,day as numbers. 
        Year has four digits or two digits assuming 20 as century.
        Must be a valid calendar day after Christ
    '''

    print "Add Event"
    dateinp = raw_input("Enter Date (yyyy,mm,dd): ")
    date = dateinp.split(',')
    if len(date)!=3 or len(date[0]) not in (2,4):
        print("invalid date")
        return None
    if len(date[0]) == 2:
        date[0] = '20'+date[0]
    date[1] = date[1].rjust(2,"0")
    date[2] = date[2].rjust(2,"0")
    try:
        d=datetime.date(*map(int,date))
    except ValueError:
        print("invalid date")
        return None
    date = '/'.join(date)
    return date

print event()

That seems to work how I want it to but when I put it into my program it doesn't. I have modified your code slightly so it fits in with mine but maybe I have done this wrong?

Here is the code:

if menu_choice == 1:
        print "Add Event"
        dateinp = raw_input("Enter Date (yyyy,mm,dd): ")
        date = dateinp.split(',')
        if len(date)!=3 or len(date[0]) not in (2,4):
            print("invalid date")
            start # restarts the loop
            continue
        if len(date[0]) == 2:
            date[0] = '20'+date[0]
        date[1] = date[1].rjust(2,"0")
        date[2] = date[2].rjust(2,"0")
        try:
            d=datetime.date(*map(int,date))
        except ValueError:
            print("invalid date")
            start # restarts the loop
            continue
        date = '/'.join(date)
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)

If I enter '20100315' it displays invalid but this should be valid. Is it something I'm doing wrong?

You're still using .split(',') for commas. Therefore, anything you type without commas won't work. If you want it without commas, try doing this:

date = '20100315'
year = date[0:4]
month = date[4:6]
day = date[6:8]

Perhaps try to implement this into your code.

I thought the line
"Enter Date (yyyy,mm,dd): ")
means, that the user have to enter the date comma separated.

No no. That's the code I showed her earlier. I guess now she's wanting to have it without commas :/ I don't know

For this regular expression can be to help.
This funtion will only return correct date format in | yyyy-mm-dd | or | yyyy/mm/dd |

import re

def foo():
    while True:
        print 'use format | yyyy-mm-dd |'
        date_input = raw_input("Enter date: ")        
        if re.match(r"(?:(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01]))\Z", date_input):
            print 'Match'
            return date_input       
        else:
            print 'No match,try again'  	

print foo()

'''-->Out
use format | yyyy-mm-dd |
Enter date: 2000-13-25
No match,try again
use format | yyyy-mm-dd |
Enter date: 2000-12-25
Match
2000-12-25
'''

I am unsure as to the best way of formatting the date. I am very confused as this is still all very new to me.

I have recently decided it would be best if the user just entered yyyymmdd and the program to add in the '/' but I am very confused with all of the code.

Sorry to confuse you all.

There is no confusion about how my function work.
It will return a correct date format in yyyymmdd an nothing else.

I know regular expression is not easy to learn and can be confusing.
The other way is to check every number with range function or a tuple version.
Look at this post here you see how to check that numbers are correct without regular expression.
http://www.daniweb.com/forums/thread265942.html

You can look a datetime module and see if it have a check for date format.
http://docs.python.org/library/datetime.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.