如何在Python中将字符串转换为日期时间?

huangapple go评论52阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年2月6日 14:17:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定