python-mysqlHow can I use Python to convert a MySQL datetime value to a different format?
Python can be used to convert a MySQL datetime value to a different format by using the datetime module and the strftime() function. The following example code illustrates this:
# import datetime module
import datetime
# define the datetime value
datetime_value = '2020-08-01 12:30:00'
# convert the string into a datetime object
datetime_object = datetime.datetime.strptime(datetime_value, '%Y-%m-%d %H:%M:%S')
# convert the datetime object into a different format
new_datetime_format = datetime_object.strftime('%B %d, %Y %H:%M')
# print the new datetime format
print(new_datetime_format)
Output example
August 01, 2020 12:30
Code explanation
import datetime
: imports the datetime module which contains the necessary functions for manipulating date and time values.datetime_value = '2020-08-01 12:30:00'
: defines the datetime value as a string.datetime_object = datetime.datetime.strptime(datetime_value, '%Y-%m-%d %H:%M:%S')
: converts the string into a datetime object using the strptime() function.new_datetime_format = datetime_object.strftime('%B %d, %Y %H:%M')
: converts the datetime object into a different format using the strftime() function.print(new_datetime_format)
: prints the new datetime format.
Helpful links
More of Python Mysql
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to query MySQL with multiple conditions?
- How can I connect Python and MySQL?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...