Python formatted strings and datetime

3.3k Views Asked by At

Is this not allowed or did I type something wrong?

import datetime

print(f"Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}"
Syntax error at %I:%M...
                  ^
5

There are 5 best solutions below

0
Ammar On
 print(f'Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}')

Quotes bro.

0
Jojo On

You are ending your fstring by using double quotes in your strftime() function, use single quotes or escape them.

For example:

print(f"Current Time: {datetime.datetime.now().strftime('%I:%M:%S %p')}"

Also, not related to your question, but you are not really using fstrings in the right way.

It would look a lot nicer if you defined a 'current time' variable and then put it in your fstring.

For example:

current_time = datetime.datetime.now().strftime('%I:%M:%S %p')

print(f"Current Time: { current_time }")

0
Life Whiz On

The datetime class already has a pre-configured date to string method : strftime()

So your code can look something like this :

import datetime

date_today = datetime.datetime.now()
date_today.strftime('%I:%M:%S %p')
0
Vishwas On

Its because of quotes. Here is workaround method and your original method.

import datetime
print (f'Current Time : {datetime.datetime.now().strftime("%I:%M:%S %p")}')


import datetime
d = datetime.datetime.now().strftime("%I:%M:%S %p")
print(f"Current Time: {d}")
0
djvg On

Why not like this:

from datetime import datetime
    
print(f'Current Time: {datetime.now():%I:%M:%S %p}')

See PEP498.