英文:
How to convert string into datetime in python?
问题
在数据框中,如果日期列的子集是02.03(月.日),我应该如何将其转换为日期时间格式,以便在导出到Excel时将子集保存为日期格式。
reference_date_str = reference_date
reference_date_obj = datetime.strptime(reference_date_str, '%y-%m-%d')
英文:
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')
答案1
得分: 2
你需要确保传递的格式与字符串的结构相匹配。如果字符串中使用点号,那么格式结构应该类似。
这应该解决问题:
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)
输出:
2023-02-03 00:00:00
英文:
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
答案2
得分: 1
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 an Excel sheet, you can pass the date in any format as long as you specify the format in your statement:
pd.ExcelWriter("abc.xlsx", engine='xlsxwriter', date_format='YYYY.MM.DD')
英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论