I’m pretty new to Python, so hopefully the problem I’m having has a simple solution.
At work we always us either Shell (ksh) or Perl for all of our scripting work. Since python has been shipped with Solaris for some time now, it has (finally) been given the green light as a scripting platform. I’ve started prototyping some improvements to our scripts using Python.
What I’m trying to accomplish is taking a time stamp and a string representing a time stamp and creating a datetime object for some 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 the 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: an integer is required
I don’t understand why I’m getting this TypeError exception. My understanding of Python’s dynamic typing is that I shouldn’t need to convert a string to an integer if the string is all digits.
So the problem would seem to be I’m either missing something that I need, or my understanding of the language is flawed.
Any help would be greatly appreciated. Thanks.
Strongly consider using datetime.datetime.strptime:
Or, if you install the third-party module, dateutil, you could parse it like this:
Notice that dateutil tries to parse the string without you explicitly declaring the format. This has to be used carefully (with testing and control over admissible input strings) since otherwise there are ambiguous dates which dateutil may parse incorrectly.