Friday, February 8, 2013

Get UTC in python 2.5

This turns out to be quite native. Corresponding to functions like now() there is a utcnow(), etc. There is a function called strftime to convert a time value to a string with all the usual formatting. Sadly, for whatever version of python 2.5 that I have, the formatting option %f for milliseconds doesn't seem to work, even though if I just print() the time value it prints the milliseconds.

Here is a link that talks about utcnow(). It's in the question, but the rest of this thread is garbage:

http://stackoverflow.com/questions/1599060/how-can-i-get-an-accurate-utc-time-with-python

Here's a great review of the many possible ways to get the current time:

http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python

Among my favorites are:

import datetime

datetime.now()
-or-
datetime.utcnow()

or:

import gmtime,strftime

strftime("%Y%m%d_%H%M%S.%f", gmtime())

or:

import datetime
datetime.datetime.now.().strftime("%Y%m%d_%H%M%S.%f")

see:
http://pleac.sourceforge.net/pleac_python/datesandtimes.html

or apparently now can just be called on its own?

import datetime
now.strftime("%Y%m%d_%H%M%S.%f")

(not quite. See: http://effbot.org/librarybook/datetime.htm

So, here's some info about no %f:

This link for strftime doesn't show %f as a formatting option:

http://www.tutorialspoint.com/python/time_strftime.htm

This link clears things up a bit, apparently time.strftime doesn't support milli-or-miro seconds, but other functions do. Also if the system doesn't support milliseconds, that is a cause of grief:

http://stackoverflow.com/questions/6677332/using-f-with-strftime-in-python-to-get-microseconds

Whenever I tried %f on my system, no result would be produced at all (silent failure). I got around that by using str() which does a conversion including milliseconds but doesn't seem to accept formatting and then just substituting out the characters I didn't want:

timeformatted= str(datetime.datetime.utcnow())

timeformatted = timeformatted.replace("-","")
timeformatted = timeformatted.replace(":","")
timeformatted = timeformatted.replace(" ","_")

This forum thread's commenters repeatedly urged the use of the funtion "translate", I'm not sure why I used replace instead:

http://stackoverflow.com/questions/10017147/python-replace-characters-in-string