Hi

I want to prompt the user to enter the date dd/mm/year and use this later as part of filename and later as object in file(if this helps searching). Does using datetime ensure that user input will be a valid input? I would like the output to be year-mm-dd

My below version errors.

#This doesn't error but also doesn't prompt me for input.

from datetime import date
def ObtainDate():
   input = raw_input("Type Date dd/mm/year: ")
   d = datetime.strptime(input, "%y-%m-%d")
print ObtainDate

Edited 7 Years Ago by flebber: n/a

Firstly 'input' is a reserved word in python, it's used to get input from the user, (rather like raw_input!). So that's why this line of code fails to do anything:

input = raw_input("Type Date dd/mm/year: ")

Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!

Secondly...No I don't think that strptime will work used like that! if your users enter anything other than yy-mm-dd, it will bomb out with an error!
But if you use a try: except: block inside a loop, you should be able to get the user to repeatedly enter the date until the format is correct!

Check this out:

import datetime
def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d = datetime.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
        except:
            print "Doh, try again!\n"
    return d

#test the function
print ObtainDate()

I've not done any exception handling code for a while, but there should be a way of outputting to the user the reason that the exception occurred.

I'll leave that up to you to look up!

Cheers for now,
Jas

Firstly 'input' is a reserved word in python, it's used to get input from the user, (rather like raw_input!). So that's why this line of code fails to do anything:

input = raw_input("Type Date dd/mm/year: ")

Change your variable 'input' to something like 'userInput' or just anything that isn't a reserved word and you will get your prompt!

Secondly...No I don't think that strptime will work used like that! if your users enter anything other than yy-mm-dd, it will bomb out with an error!
But if you use a try: except: block inside a loop, you should be able to get the user to repeatedly enter the date until the format is correct!

Check this out:

import datetime
def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d = datetime.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
        except:
            print "Doh, try again!\n"
    return d

#test the function
print ObtainDate()

I've not done any exception handling code for a while, but there should be a way of outputting to the user the reason that the exception occurred.

I'll leave that up to you to look up!

Cheers for now,
Jas

Awesome I like it just one question why does the line below have datetime twice?

d = datetime.datetime.strptime(userIn, "%d/%m/%y")

I think with exception handling that getting the user a reason as to why input was wrong could use the try: obj.method but I will need to look into this further.

Awesome I like it just one question why does the line below have datetime twice?

d = datetime.datetime.strptime(userIn, "%d/%m/%y")

It's the only way I could access the strptime function.
The first datetime refers to the datetime package, the second refers to the datetime class.

In my import I could have used something like:

import datetime as dt

This gives the datetime package an alias (dt). So to call the strptime function I'd need to use:

dt.datetime.strptime(userInput, pattern)

So my strptime function call breaks into the following parts:
packageName.className.function(parameter1, parameter2)
or:
datetime.datetime.strptime(userInput, "%d/%m/%y")

Hope that clarifies things for you!

Cheers for now,
Jas.

Edited 7 Years Ago by JasonHippy: n/a

To find the error class simply create the error ...

import datetime as dt

# the date has to be entered in dd/mm/yy format
# entering dd/mm/yyyy by mistake will create an error
# the error class will be --> ValueError
test_date = "15/07/2003"

d1 = dt.datetime.strptime(test_date, "%d/%m/%y")

Also be aware that d1 will be a datetime object and not a string, so you have to do some simple extra coding ...

import datetime as dt

# date has been entered in dd/mm/yy format
test_date = "15/07/03"

d1 = dt.datetime.strptime(test_date, "%d/%m/%y")

print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>

# convert datetime object to a 10 character string
d2 = str(d1)[:10]

print d2, type(d2)  # 2003-07-15 <type 'str'>

# now you can use string d2 to create filenames
fname = "data.dat"
new_fname = d2 + fname

print new_fname  # 2003-07-15data.dat

This file name should sort well.

Edited 7 Years Ago by vegaseat: n/a

I really like it a lot, and it works well :) thanks jasonHippy and Vegaseat. The only thing I am going to look into when I am not so tired is that if you supply a correctly formatted date but say you use the 31st September as 31/09/09 which doesn't exist it errors "Try again! dd/mm/yy" intimating its a format error when its a date doesn't exist error.

Which simply means I need to catch 2 errors.

mport datetime as dt
def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
#Perhaps set another try here.
            print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>
            "convert datetime object to a 10 character string"
            d2 = str(d1)[:10]
            print d2, type(d2)  # 2003-07-15 <type 'str'>
        except:
            print "Try again! dd/mm/yy\n"
    Fname = "data.dat"
    newFname = d2 + Fname
    return newFname
print ObtainDate()  # 2003-07-15data.dat

Edited 7 Years Ago by flebber: tired

You can trap error details this way:

import datetime as dt

def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
#Perhaps set another try here.
            print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>
            "convert datetime object to a 10 character string"
            d2 = str(d1)[:10]
            print d2, type(d2)  # 2003-07-15 <type 'str'>
        except ValueError, what_error:
            print what_error
            print "Try again! dd/mm/yy\n"
    Fname = "data.dat"
    newFname = d2 + Fname
    return newFname

print ObtainDate()  # 2003-07-15data.dat

You can trap error details this way:

import datetime as dt

def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
#Perhaps set another try here.
            print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>
            "convert datetime object to a 10 character string"
            d2 = str(d1)[:10]
            print d2, type(d2)  # 2003-07-15 <type 'str'>
        except ValueError, what_error:
            print what_error
            print "Try again! dd/mm/yy\n"
    Fname = "data.dat"
    newFname = d2 + Fname
    return newFname

print ObtainDate()  # 2003-07-15data.dat

Much neater than a nested exception

This question has already been answered. Start a new discussion instead.