working with time

This is the place for queries that don't fit in any of the other categories.

working with time

Postby portia » Sat Jun 22, 2013 8:03 am

Hi,

The idea is as follows:
User is asked to provide time (ddmmyyyyy) or press enter to use today's day. The problem with my code is that if I specify the date, eg: 02032013, the leading zeros for day and month get truncated leaving the date as 232013. How can I solve it. Also, if you see any other problems with my code, please point it out. Thank you.

Code: Select all
import time


def input_data():
    entry_date = input("Date (ddmmyyyy or blank for today's date): ")
    if entry_date:
        try:
            strip_date = time.strptime(entry_date, '%d%m%Y')
            valid_date = str(strip_date.tm_mday) + str(strip_date.tm_mon) + str(strip_date.tm_year)
            print(valid_date)
        except ValueError:
            print("Invalid date!")
    else:
        valid_date = time.strftime("%d%m%Y", time.gmtime())
        print(valid_date)


def main():
    input_data()

if __name__ == "__main__":
    main()
portia
 
Posts: 17
Joined: Sun Apr 14, 2013 10:03 pm

Re: working with time

Postby hansn » Sat Jun 22, 2013 9:25 am

EDIT: Look at Yoriz' answer :)


An alternative is to use the string formatting % character (I don't know what it's called):
Code: Select all
>>> val = strptime('03', '%d')
>>> day = val.tm_mday
>>> print '%02d' % day
03
>>>



Hope this helps.
Last edited by hansn on Sat Jun 22, 2013 10:01 am, edited 2 times in total.
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: working with time

Postby Yoriz » Sat Jun 22, 2013 9:33 am

Hi,
Instead of
Code: Select all
valid_date = str(strip_date.tm_mday) + str(strip_date.tm_mon) + str(strip_date.tm_year)

use
Code: Select all
valid_date = time.strftime("%d%m%Y", strip_date)

Code: Select all
import time


def input_data():
    entry_date = input("Date (ddmmyyyy or blank for today's date): ")
    if entry_date:
        try:
            strip_date = time.strptime(entry_date, '%d%m%Y')
            valid_date = time.strftime("%d%m%Y", strip_date)
            print(valid_date)
        except ValueError:
            print("Invalid date!")
    else:
        valid_date = time.strftime("%d%m%Y", time.gmtime())
        print(valid_date)


def main():
    input_data()

if __name__ == "__main__":
    main()

Code: Select all
Date (ddmmyyyy or blank for today's date): 02032013
02032013
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: working with time

Postby portia » Sat Jun 22, 2013 10:31 am

Thanks a lot!
portia
 
Posts: 17
Joined: Sun Apr 14, 2013 10:03 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 4 guests