开发者

Date converter in python

def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    date_list = dat开发者_如何学运维e_string.split('/')
    import datetime
    d = datetime.date
    d.strftime('%B %d, %Y')

main()

That's what I have so far I keep getting a 0 for an output in help would be appreciated I am trying to have someone input a numerical date and the program convert it to a date like November 15, 2010


import datetime
def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    d=datetime.datetime.strptime(date_string,'%m/%d/%Y')
    print(d.strftime('%B %d, %Y'))

if __name__=='__main__':
    main()
  1. If you try to split date_string with date_string.split('/'), then you have to convert the list of strings into a list of ints. It's possible, but more work than necessary. Use datetime.datetime.strptime instead.

  2. Put all imports at the top of the script. It makes it easier to understand the dependencies of the script.

  3. In general, it's a good habit to use if __name__=='__main__' so that your scripts are importable (without inadvertently running code). This makes your scripts double-purposed -- you can run them as scripts from the command line, and also import them to reuse functions.

  4. You might also want to check out the third-party module dateutil -- it has a fuzzy date parser which can handle many formats.


The parser from dateutil is your friend.

You'll have to pip install dateutil but you've safe bags and bags of date conversion code:

pip install python-dateutil

You can use it like this.

from dateutil import parser
ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats.
date = parser.parse(ds)

ds = '12/23/2001' # or any date sting of differing formats.
date = parser.parse(ds)

You'll find you can deal with almost any date string formats with this parser and you'll get a nice standard python date back

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜