[sf-lug] unix time conversion
Jeffrey Malone
ieatlint at tehinterweb.com
Mon Oct 27 18:44:00 PDT 2008
strptime() is indeed the correct function.
See http://www.python.org/doc/2.5.2/lib/module-time.html for usage
information (it's formatting borrows the strftime conversion
specifiers as described in that big table)
Here is how you do it:
import time
string = "July 3, 1945"
# This reads the string as a time value structure. You copy for the
formatting of the string above, replacing
# the variables with conversion specifiers (eg, "%B"). Notice how the
comma is written after the %d, just as it is after the numeral 3 in
the string.
timestruct = time.strptime( string, "%B %d, %Y" )
# Note that when you imprecisely give it a time it will fill in
undefined values with defaults.
# In this case, we did not specify a the hour, minute, second (and a
couple other things). As such, they will default to 0 -- meaning, it
will read the time as "July 3, 1945 00:00:00" (as in, midnight).
# Also, as this is a UNIX epoch, it is without timezone, which can be
worth noting to avoid potential confusion.
# mktime takes a time value struct and returns a UNIX epoch timestamp
representing it (as a float -- although with this usage it should
always be an integer)
epoch = time.mktime( timestruct )
print epoch
##eof
On Mon, Oct 27, 2008 at 4:38 PM, Jim Cortez <jim at jimcortez.com> wrote:
> That is a pretty tough problem as it deals with natural language recognition.
> You can use something like http://labix.org/python-dateutil to try and parse
> several known representations of dates. Taking a machine-readable time and
> parsing into human readable is much easier.
> Hope that helps!
> Jim
>
> On Monday 27 October 2008 4:02:52 pm Alex Kleider wrote:
>> sorry, I should have written:
>> >>> string = "July 3, 1945"
>> >>> import time
>> >>> unix_time = time(string)
>> >>> print unix_time
>> >
>> > Got it!
>> >
>> > Now that you have wetted my appetite:
>> > How to change a human readable time into 'unix
>> > time?'
>> > (preferably using python so this becomes applicable to the
>> > ThinkPython grp)
>> >
>> > >>> string = "July 3, 1945"
>> > >>> import time
>> > >>> time(string)
>> >
>> > the above doesn't work but is it just because the
>> > format of the date is incorrect or is there a bigger
>> > problem?
>>
>> _______________________________________________
>> sf-lug mailing list
>> sf-lug at linuxmafia.com
>> http://linuxmafia.com/mailman/listinfo/sf-lug
>
>
> _______________________________________________
> sf-lug mailing list
> sf-lug at linuxmafia.com
> http://linuxmafia.com/mailman/listinfo/sf-lug
>
More information about the sf-lug
mailing list