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 connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database using an Xserver?
- How can I troubleshoot a Python MySQL OperationalError?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to handle MySQL NULL values?
See more codes...