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 can I use multiple cursors in Python to interact with MySQL?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I access MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect to MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I use the MySQL Connector in Python?
- How do I connect Python with MySQL using XAMPP?
See more codes...