【问题标题】:Error changing datetime format from python to SQL Server将日期时间格式从 python 更改为 SQL Server 时出错
【发布时间】:2021-07-16 02:06:40
【问题描述】:

我正在使用 Python 将我的数据加载到 SQL Server 中。我想将ScheduledStartDate 的格式从“20-APR-2021 09:00:00 AM”更改为“2021-04-20 09:00:00”

df['ScheduledStartDate'] = pd.to_datetime(df['ScheduledStartDate'])
df['ScheduledStartDate'] = df['ScheduledStartDate'].dt.strftime('%Y-%m-%d %H:%M:%S')

但是,我得到了这个错误

将 nvarchar 数据类型转换为 datetime 数据类型导致值超出范围。

【问题讨论】:

标签: python sql sql-server


【解决方案1】:

在 SQL Server 中,datetimedata type,即 ScheduledStartDate 列的类型。在内部,您在该表中插入的日期并未真正格式化,您可以阅读此post 的第一个失败关于此常见错误的信息。但是,当您执行 SELECT 并将日期格式设置为 20-APR-2021 09:00:00 AM 时,并不是因为它是以这种方式存储的,它只是以默认格式显示并与您的操作系统日期格式首选项匹配。

话虽如此,您应该从 python 存储日期而不对其进行格式化,然后在检索日期时间列时对其进行格式化。喜欢:

SELECT CONVERT(varchar,ScheduledStartDate,20), *
FROM table

其中20Date Format Codeyyyy-mm-dd hh:mm:ss

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多