How can I format the output of localtime?

Asked by Dino Conte

Sometimes, i get the result "2012-08-05 21:05:33.000006" with the command "ephem.localtime()". However, I would "2012-08-05 21:05:33".

The result of the code is:

conte@scheideweg:~/Downloads$ python p.py
Sonnenaufgang: 2012-08-06 06:08:26 Lokale Zeit
Sonnenuntergang: 2012-08-05 21:05:33.000006 Lokale Zeit
conte@scheideweg:~/Downloads$

Example code:

#!/usr/local/bin/python

import ephem
import math

home = ephem.Observer()
home.long = "7.29965"
home.lat ="51.13820"
home.elevation = 308
home.date = ephem.now()

hza = math.acos(ephem.earth_radius / (home.elevation + ephem.earth_radius))

home.horizon = hza

sun = ephem.Sun()

sunrise = home.next_rising(sun)
sunset = home.next_setting(sun)

print "Sonnenaufgang: ", ephem.localtime(sunrise), "Lokale Zeit"
print "Sonnenuntergang: ", ephem.localtime(sunset), "Lokale Zeit"

Question information

Language:
English Edit question
Status:
Solved
For:
PyEphem Edit question
Assignee:
No assignee Edit question
Solved by:
Brandon Rhodes
Solved:
Last query:
Last reply:
Revision history for this message
Best Brandon Rhodes (brandon-rhodes) said :
#1

I cannot reproduce your problem on my current machine (Python 2.7.3) but I can point you in the direction of lots of documentation, because the object returned by PyEphem's localtime() function is not a string, but a Python "datetime":

>>> print type(ephem.localtime(sunset))
<type 'datetime.datetime'>

I am not sure why a datetime would make the rounding error that you are encountering, but you can probably ask it to omit the microseconds entirely by setting its microseconds to zero:

def seconds_only(t):
    s = ephem.localtime(t)
    t.microseconds = 0
    return s

Alternatively, you could get the returned value and chop off everything past the 19th character and the “.0000006” string would thus get chopped off:

ephem.localtime(sunset)[:19]

But, anyway, here is the extensive documentation on the "datetime" and how it works — hopefully you can get it to behave on your platform — good luck!

http://docs.python.org/dev/library/datetime.html

Revision history for this message
Dino Conte (dermitdemdino) said :
#2

Thanks Brandon Rhodes, that solved my question.