Saturday, December 28, 2024
Google search engine
HomeLanguagesConvert datetime string to YYYY-MM-DD-HH:MM:SS format in Python

Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python

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




# import datetime module
from datetime import datetime
 
# consider date in string format
my_date = "30-May-2020-15:59:02"
 
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
 
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
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




# import datetime module
from datetime import datetime
 
# consider date in string format
my_date = "30-May-2020-15:59:02"
 
# convert datetime string into date,month,day
# and hours:minutes:and seconds format using
# strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
 
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))
 
# consider date in string format
my_date = "04-Jan-2021-02:45:12"
 
# convert datetime string into date,month,day
# and hours:minutes:and seconds format using
# strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
 
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))
 
# consider date in string format
my_date = "23-May-2020-15:59:02"
 
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
 
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
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
RELATED ARTICLES

Most Popular

Recent Comments