Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
There are multiple methods to convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python. Here are some of them:
Method 1: Using datetime.strptime() and strftime() functions
from datetime import datetime
# datetime string in original format
datetime_str = '2022-01-01 12:30:45'
# convert datetime string to datetime object
datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
# convert datetime object to desired format
formatted_datetime_str = datetime_obj.strftime('%Y-%m-%d-%H:%M:%S')
print(formatted_datetime_str) # output: 2022-01-01-12:30:45
In this method, we first convert the datetime string to a datetime object using the datetime.strptime()
function. We pass the datetime string and its format as arguments to this function. The format string '%Y-%m-%d %H:%M:%S'
specifies the order and format of the year, month, day, hour, minute, and second in the datetime string.
Next, we convert the datetime object to the desired format using the strftime()
function. We pass the desired format string '%Y-%m-%d-%H:%M:%S'
as an argument to this function. This format string specifies the order and format of the year, month, day, hour, minute, and second in the desired format.
Method 2: Using pandas.to_datetime() and strftime() functions
import pandas as pd
# datetime string in original format
datetime_str = '2022-01-01 12:30:45'
# convert datetime string to datetime object
datetime_obj = pd.to_datetime(datetime_str)
# convert datetime object to desired format
formatted_datetime_str = datetime_obj.strftime('%Y-%m-%d-%H:%M:%S')
print(formatted_datetime_str) # output: 2022-01-01-12:30:45
In this method, we use the pd.to_datetime()
function from the pandas library to convert the datetime string to a datetime object. This function automatically infers the format of the datetime string, so we don't need to specify the format string explicitly.
Next, we convert the datetime object to the desired format using the strftime()
function, as in the previous method.
Method 3: Using dateutil.parser.parse() and strftime() functions
from dateutil.parser import parse
# datetime string in original format
datetime_str = '2022-01-01 12:30:45'
# convert datetime string to datetime object
datetime_obj = parse(datetime_str)
# convert datetime object to desired format
formatted_datetime_str = datetime_obj.strftime('%Y-%m-%d-%H:%M:%S')
print(formatted_datetime_str) # output: 2022-01-01-12:30:45
In this method, we use the parse()
function from the dateutil.parser
module to convert the datetime string to a datetime object. This function can handle a wide variety of datetime formats, so we don't need to specify the format string explicitly.
Next, we convert the datetime object to the desired format using the strftime()
function, as in the previous methods.