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?
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.
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().
"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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With