Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.7.0: How do I format datetime to mm-dd-yy hh:mm:ss?

How do I format datetime to mm-dd-yy hh:mm:ss? I did it using the following code:

import datetime
t = datetime.datetime.now()

s = str(format(t.second, '02d'))
m = str(format(t.minute, '02d'))
h = str(format(t.hour, '02d'))

d = str(format(t.day, '02d'))
mon = str(format(t.month, '02d'))
y = str(t.year)

x = '-'
z = ':'
print(mon + x + d + x + y + '   ' + h + z + m + z + s)

but the problem is, first of all, the year prints in YYYY instead of YY (I only want the last two digits of the year). Second of all, I'm sure there's an easier way to print datetime in mm-dd-yy hh:mm:ss instead of doing it manually like I did. Please help. Thanks.

like image 803
SNN Avatar asked Oct 18 '25 06:10

SNN


1 Answers

Like this:

import datetime

now = datetime.datetime.now()
now.strftime('%m-%d-%y %H:%M:%S')

Also see docs - https://docs.python.org/3/library/datetime.html

like image 196
Yani Avatar answered Oct 20 '25 00:10

Yani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!