scripting - Python datetime TypeError, integer expected -


i'm pretty new python, problem i'm having has simple solution.

at work either shell (ksh) or perl of our scripting work. since python has been shipped solaris time now, has (finally) been given green light scripting platform. i've started prototyping improvements our scripts using python.

what i'm trying accomplish taking time stamp , string representing time stamp , creating datetime object date arithmetic.

my example code follows:

#!/bin/python  import datetime  filetime="201009211100" format = "yyyymmdd"  yidxs = format.find('y') yidxe = format.rfind('y')  if not filetime[yidxs:yidxe+1].isdigit():     print "error: year in wrong format"     exit else:     print "year [" + filetime[yidxs:yidxe+1] + "]"  midxs = format.find('m') midxe = format.rfind('m')  if not filetime[midxs:midxe+1].isdigit():     print "error: month in wrong format"     exit else:     print "month [" + filetime[midxs:midxe+1] + "]"  didxs = format.find('d') didxe = format.rfind('d')  if not filetime[didxs:didxe+1].isdigit():     print "error: day in wrong format"     exit else:     print "day [" + filetime[didxs:didxe+1] + "]"   old = datetime.date( filetime[yidxs:yidxe+1], \                      filetime[midxs:midxe+1], \                      filetime[didxs:didxe+1] ); 

i'm getting following output/error:

year [2010] month [09] day [21] traceback (most recent call last):   file "./example.py", line 37, in <module>     filetime[didxs:didxe+1] ); typeerror: integer required 

i don't understand why i'm getting typeerror exception. understanding of python's dynamic typing shouldn't need convert string integer if string digits.

so problem seem i'm either missing need, or understanding of language flawed.

any appreciated. thanks.

strongly consider using datetime.datetime.strptime:

import datetime  tests=["201009211100","201009211199"] filetime in tests:     try:         date=datetime.datetime.strptime(filetime,'%y%m%d%h%m')         print(date)     except valueerror err:         print(filetime,err)  # 2010-09-21 11:00:00 # ('201009211199', valueerror('unconverted data remains: 9',)) 

or, if install third-party module, dateutil, parse this:

in [106]: import dateutil.parser dparser  in [107]: dparser.parse('201009211100') out[107]: datetime.datetime(2010, 9, 21, 11, 0) 

notice dateutil tries parse string without explicitly declaring format. has used (with testing , control on admissible input strings) since otherwise there ambiguous dates dateutil may parse incorrectly.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -