Skip to content
Advertisement

How to format a mysql datetime yyyy-mm-dd to dd-mm-yyyy in Python?

My python code retrieves a datetime column from a mySql server database. I can print the datetime as it is stored on the server (ex. 2018-10-22, however I need to print it in a more readable way like 22-10-2018. Basically, row[0] holds datetime data as the code below. Thanks for any help.

if mycursor.rowcount > 0:

print("Total rows are:  ", len(myresult))
for row in myresult:
  print("Record Number: " + str(countLines))
  print("-----------------")
  print("Time: ", row[0])
  print("Latitude: ", row[1])
  print("Longitude: ", row[2])
  print("Accuracy: ", row[3])
  print("Place: ", row[4])

Advertisement

Answer

If your time is a datetime object you can use strftime()

from datetime import datetime

row[0].strftime('%d-%m-%Y')

Output

t = datetime(2018, 10, 22)
t.strftime('%d-%m-%Y')

#'22-10-2018'

If your data is a string you will need to define it as a datetime object first.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement