【发布时间】:2018-10-14 16:22:38
【问题描述】:
我有一个问题,在其他 stackoverflow 页面上以不同方式讨论过,但我找不到任何可以解决我奇怪问题的解决方案。我有一个 Excel 文件(.xlsx),我读取并存储在数据框中。其中一列称为“时间”,数据格式为“2018/10/13 14:29:00”。 在我的 python 脚本中,我需要将此列从对象类型(这是我在查询 python 时可以看到的类型)转换为 datetime 并将这种新格式保存在一个名为“date_time_fmt”的新列中。
这实际上是我的脚本,我在其中尝试了我在 stackoverflow 中找到的所有可能的解决方案:
try:
df_accounts_followed['date_time_fmt'] = df_accounts_followed['time'].astype('datetime64[ns]')
except Exception as e:
print("Error 1")
exception_short_name = type(e).__name__
print("Error Type: {}".format( exception_short_name))
print("Error description: {}".format( e))
try:
df_accounts_followed['time'] = df_accounts_followed['time'].astype('|S')
name_dtype = df_accounts_followed['time'].dtype.name
print("df_accounts_followed['time'] is now of type: {}".format(name_dtype))
df_accounts_followed['date_time_fmt'] = df_accounts_followed['time'].astype('datetime64[s]')
except Exception as e:
try:
print("Error 2")
exception_short_name = type(e).__name__
print("Error Type: {}".format( exception_short_name))
print("Error description: {}".format( e))
df_accounts_followed['date_time_fmt'] = pd.to_datetime(df_accounts_followed['time'], format = '%Y/%m/%d %H:%M:%S')
except Exception as e:
print("Error 3")
exception_short_name = type(e).__name__
print("Error Type: {}".format( exception_short_name))
print("Error description: {}".format( e))
try:
df_accounts_followed['date_time_fmt'] = df_accounts_followed['time'].apply(lambda x: datetime.strptime(x,'%Y/%m/%d %H:%M:%S'))
except Exception as e:
print("Error 4")
print("Error line num: {}".format(sys.exc_info()[-1].tb_lineno))
exception_short_name = type(e).__name__
print("Error Type: {}".format( exception_short_name))
print("Error description: {}".format( e))
input("Enough !")
现在,当我运行脚本时,会发生这种情况。第一次尝试出现此错误:
Error when filtering df_excel_actions_report dataframe.
Error Type: ValueError
Error description: Error parsing datetime string "2018/10/13 14:29:00" at position 4
这是我第二次尝试后得到的错误:
Error Type: ValueError
Error description: Error parsing datetime string "2018/10/13 14:29:00" at position 4
这是我第三次尝试后得到的错误:
Error Type: TypeError
Error description: <class 'bytes'> is not convertible to datetime
这是我上次尝试时遇到的错误:
Error Type: TypeError
Error description: strptime() argument 1 must be str, not bytes
此时我的绝望程度相当高。我希望有人可以帮助我。这些是我阅读的一些页面:time.strptime() - argument 0 must be str, not bytes、Convert Pandas Column to DateTime II、pandas convert string columns to datetime, allowing missing but not invalid。 谢谢
【问题讨论】:
标签: python python-3.x datetime dataframe