Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
Last Updated :
19 Dec, 2022
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used.
strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds
Syntax:
datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”)
strftime() is used to convert DateTime into required timestamp format
Syntax:
datetime.strftime(“%Y-%m-%d-%H:%M:%S”)
Here,
- %Y means year
- %m means month
- %d means day
- %H means hours
- %M means minutes
- %S means seconds.
First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime
Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
from datetime import datetime
my_date = "30-May-2020-15:59:02"
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S" )
print (d.strftime( "%Y-%m-%d-%H:%M:%S" ))
|
Output
'2020-05-30-15:59:02'
Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
from datetime import datetime
my_date = "30-May-2020-15:59:02"
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S" )
print (d.strftime( "%Y-%m-%d-%H:%M:%S" ))
my_date = "04-Jan-2021-02:45:12"
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S" )
print (d.strftime( "%Y-%m-%d-%H:%M:%S" ))
my_date = "23-May-2020-15:59:02"
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S" )
print (d.strftime( "%Y-%m-%d-%H:%M:%S" ))
|
Output
2020-05-30-15:59:02
2021-01-04-02:45:12
2020-05-23-15:59:02
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...