Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
markmnl Avatar asked Feb 07 '14 02:02

markmnl


People also ask

How do I format a datetime string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I format a string in Python 3?

Method 2: Formatting string using format() method Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str. format().

What does {: 3f mean in Python?

"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.


1 Answers

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' 
like image 73
falsetru Avatar answered Sep 23 '22 16:09

falsetru