-1

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • What format / object type is your date ? datetime.time object ? – Mateo Vial Feb 25 '22 at 03:13
  • I have an integer number and based on .apply(datetime.fromtimestamp) I have the date with hours and minutes and seconds. –  Feb 25 '22 at 03:19

2 Answers2

1
  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'
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • Thanks. However, when I run this code I got this error: ''Series' object has no attribute 'strftime' –  Feb 25 '22 at 03:18
  • Sounds like you're using `pandas`. Try asking a new question with that information included in it. I'm guessing what you want is https://stackoverflow.com/questions/30132282/datetime-to-string-with-series-in-pandas – Mateen Ulhaq Feb 25 '22 at 03:24
0

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".

Valera Grishin
  • 441
  • 3
  • 9