Entry
How can I convert an ascii formatted date into integer time in seconds since 1970?
Aug 9th, 2000 03:28
unknown unknown, Stuart Ford, Aahz Maruch
Not a single function, but you can use the time.strptime function, and
pass its result to the time.mktime function. The only problem is that
this doesn't work on Windows machines.
*nix Example:
TimeStr = "Jan 12 1999 20h23"
MyTime = int(time.mktime(time.strptime(TimeStr, "%b %d %Y %Hh%M")))
For a Windows Machine, you must parse the string yourself and use the
time.mktime function to return the Time integer.
Windows Example:
import re
import time
import string
def GetMonth(str):
str = string.upper(str)
if str == 'JAN':
return 1
elif str == 'FEB':
return 2
elif str == 'MAR':
return 3
elif str == 'APR':
return 4
elif str == 'MAY':
return 5
elif str == 'JUN':
return 6
elif str == 'JUL':
return 7
elif str == 'AUG':
return 8
elif str == 'SEP':
return 9
elif str == 'OCT':
return 10
elif str == 'NOV':
return 11
elif str == 'DEC':
return 12
else:
return 0
def ParseDateString(TimeStr):
match = r'(?P<month>\D*) (?P<day>\d*) (?P<year>\d*)
(?P<hour>\d*)h(?P<minute>\d*)'
reMatch = re.compile(match)
DateTimeFound = reMatch.search(TimeStr)
DateTimeDict = DateTimeFound.groupdict()
Year = string.atoi(DateTimeDict['year'])
Month = GetMonth(DateTimeDict['month'])
Day = string.atoi(DateTimeDict['day'])
Hour = string.atoi(DateTimeDict['hour'])
Minute = string.atoi(DateTimeDict['minute'])
return int(time.mktime((Year, Month, Day, Hour, Minute, 0, 0, 0, 0))
-------
And yes, I know there are much easier ways to get the month digit with
a list or dictionary, but I wanted to be very basic in case any newbies
were interested.
def GetMonth(str):
months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
return months.index(string.upper(str) )+1
or just load up a dictionary and pull the value.
-------
If you're using Windows (and even if you're not), you may want to
consider M.A. Lemburg's mxDateTime package. Look at
http://www.vex.net/parnassus to find it.