How to convert string into datetime in python?

Question:

In a dataframe, if a subset of a date column is 02.03 (month.date), how can I convert it to dateTime format so that the subsets are saved as a data format when being exported to Excel.

 reference_date_str = reference_date
 reference_date_obj = datetime.strptime(reference_date_str, '%y-%m-%d')
Asked By: Seohyun Jeong

||

Answers:

You need to make sure you pass a format that matches the structure of your string.
if the string is using dots, then the format structure should be similar.

This should do the trick:

reference_date = tr.find('td').text
reference_date_with_year = f"2023.{reference_date}"
reference_date_obj = datetime.strptime(reference_date_with_year, '%Y.%m.%d')
print(reference_date_obj)

output:

2023-02-03 00:00:00
Answered By: Meny Issakov
reference_date = '2023.' + reference_date
reference_date_obj = datetime.strptime(reference_date_str, '%Y.%m.%d')
excel_date=reference_date_obj.strftime("%Y.%m.%d")

if you are using pandas to write to excel sheet, you can pass the date in any format as long as you specify the format in your stmt

pd.ExcelWriter("abc.xlsx",engine='xlsxwriter',date_format='YYYY.MM.DD')
Answered By: geekay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.