+3 votes
in Programming Languages by (77.8k points)

I am using the datetime.now() function to get the current date and time, but it does not return the date and time in string format, e.g., '2022-09-12'. Is there any way to get the date and time in the string format?

1 Answer

+3 votes
by (73.6k points)
selected by
 
Best answer

You can use the strftime(format) function for the formatting. It returns a string representing the date, controlled by an explicit format string.

Here is an example:

>>> from datetime import datetime

>>> now = datetime.now()

>>> now.strftime('%Y-%m-%d')

'2022-09-12'

>>> now.strftime('%H:%M:%S')

'00:59:06'

Format string:

Y: 4-digit year

m: 2-digit month 

d: 2-digit date

H: 2-digit hour

M: 2-digit minute

S: 2-digit second

Related questions

+2 votes
1 answer
+1 vote
1 answer
+2 votes
1 answer
+2 votes
1 answer
+3 votes
1 answer

...