Home > Net >  Get YYYY-DD-MM from YYYY-DD-MM HH:MM:SS
Get YYYY-DD-MM from YYYY-DD-MM HH:MM:SS

Time:02-25

I have a date in the format 2012-01-01 06:00:00. I want to get only the date in the format 2012-01-01.

I've tried multiple links such as Converting (YYYY-MM-DD-HH:MM:SS) date time But, I could not find the solution.

CodePudding user response:

  1. Parse. str -> date.
from datetime import datetime

s = "2012-01-01 06:00:00"
dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
  1. Format. date -> str.
s_ymd = dt.strftime("%Y-%m-%d")

Result:

>>> s_ymd
'2012-01-01'

CodePudding user response:

Assuming your date is a string, the following works fine:

str = "2012-01-01 06:00:00"
print(str[:10])

The notation [:10] basically means "take first 10 characters of the string".

  • Related