spaceghost
spaceghost

Reputation: 35

datetime entering value when one is not specified

I'm currently learning Python and taken it upon myself to learn some data validation. One part I've gotten stuck on is date and time validation. This program takes a number of parameters including date_start, time_start, date_end, and time_end. The catch is I need them in ISO format. Once in that format I need to make sure they are valid. That's where I'm stuck.

from datetime import datetime

def validate_date(date_start, time_start, date_end, time_end):
    full_date_start = date_start + time_start
    full_date_end   = date_end + time_end

    try:
        formatted_time_start = datetime.strptime(full_date_start, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")    
        formatted_time_end = datetime.strptime(full_date_end, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")
        return True
    except ValueError:
        return False

date_start = "2017-06-29"
time_start = "16:24:00"
date_end   = "2017-06-"
time_end   = "16:50:30"

print(validate_date(date_start, time_start, date_end, time_end))
print("Date Start: " + date_start + "\nTime Start: " + time_start + "\nDate End: " + date_end + "\nTime End: " + time_end)

I was testing some of the code by removing the day for date_end and the output I got back was

2017-06-01T06:50:30

This check should have failed, or I believe it should have since a day was not supplied. Any help would be appreciated and if there is an easier way to do this, I'd take it. Thank you!

Upvotes: 2

Views: 63

Answers (1)

If you check the value of full_date_end before the line that should fail is executed, you get this: "2017-06-16:50:30" and since the format you are looking for looks like this "%Y-%m-%d%H:%M:%S" it picks up the first digit of 16 as the day value and the second digit as the hour value.

To avoid this I would suggest using this format: "%Y-%m-%d %H:%M:%S" as the second parameter of the strptime call. But this also requires for you to change the lines where you define full_date_start and full_date_end as:

full_date_start = date_start + ' ' + time_start
full_date_end = date_end + ' ' + time_end

try:
    formatted_time_start = datetime.strptime(full_date_start, "%Y-%m-%d %H:%M:%S").isoformat(sep="T", timespec="seconds")    
    formatted_time_end = datetime.strptime(full_date_end, "%Y-%m-%d %H:%M:%S").isoformat(sep="T", timespec="seconds")
    ...

I hope that solves your problem.

Upvotes: 4

Related Questions