Site Sponsors:
Time Formatting & Conversion in Python 3 
For those of yooze-guys whom may not know, Python 3.5 came out last month.


To commemorate the event, I thought that I would share a little time-conversion ditty I wrote.

Indeed, the need to understand this particular time-conversion task is so common that I remain amazed that there are - at the time of this writing - absolutely NO decent articles on converting between "military" and "civilian" time on the Internet using Python3.

Short on time as I am, please allow me to post and go - for the moment we'll let 'google do the rest:

from datetime import datetime as zdatetime
from datetime import timezone

class LogEntry():

""" Manage a GMT (i.e. Non-naive timezone) log-entry """
def _hack(self, message):
znow =
self.utc_date = znow.strftime(format=self.UFORMAT)
self.message = str(message)

def __init__(self, message):
""" Taking care of beez-nice """
self.UFORMAT = '%Y-%m-%d %H:%M:%S [%z]'
self.LFORMAT = '%Y-%m-%d %I:%M:%S %p'

def __repr__(self):
""" Get the UTC-0 (i.e. non-naive + military-time) format """
return self.utc_date + "\t" + self.message

def __str__(self):
""" Get the LOCAL (naive + civilian-time) format """
st_time = zdatetime.strptime(self.utc_date,self.UFORMAT)
ltime = st_time.astimezone()
return "[" + \
ltime.strftime(format=self.LFORMAT) + "] " \
+ self.message

def hack(self, message):
""" Update the time, as well as the message """

if __name__ == '__main__':
""" Basic proof of concept """
ent = LogEntry('This is a test')

Here is the proof of concept:

>>> ================================ RESTART ================================
2015-10-25 00:04:12 [+0000] This is a test
[2015-10-24 08:04:12 PM] This is a test



p.s: Just for the record, when logging / storing events of any worth onto servers, the anticipated & common convention remains to store said textual line-entries in a GMT / UTC-0 time format.



Add Comment
Comments are not available for this entry.