Wednesday 20 November 2019

Format time string in Python 3.3



I am trying to get current local time as a string in the format: year-month-day hour:mins:seconds. Which I will use for logging. By my reading of the documentation I can do this by:



import time
'{0:%Y-%m-%d %H:%M:%S}'.format(time.localtime())


However I get the error:





Traceback (most recent call last):
File "", line 1, in
ValueError: Invalid format specifier


What am I doing wrong? Is there a better way?


Answer



time.localtime returns time.struct_time which does not support strftime-like formatting.




Pass datetime.datetime object which support strftime formatting. (See datetime.datetime.__format__)



>>> import datetime
>>> '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
'2014-02-07 11:52:21'

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...