【问题标题】:Time Data Format Non Accepting On PostgreSQLPostgreSQL 不接受时间数据格式
【发布时间】:2021-02-15 03:45:47
【问题描述】:

我的 Outlook 日历中有一个脚本,用于更改已发布事件的日期(Django 项目)。基本上,它会查询您输入的日期并搜索事件的名称。如果存在,它将删除旧事件并发布新事件。我当前发布的代码在我的作为 SQL-Lite 后端的开发服务器上工作,我的生产服务器在带有 PostgreSQL 的 Heroku 上。它在我的生产中失败了。这是我的代码。

           print('Authenticated W/ O365')        
           # Checkes if event exists in K8 Calendar 
           calendar = schedule.get_calendar(calendar_name ="K-8")
           calendar.name = 'K-8'
           print('Checking if Event Exits in K8 Calendar')
           print("Event Name:", obj.event_name)
           print("Event Start:", obj.start_date)
           print("Event End:", obj.end_date)   
           q = calendar.new_query('start').equals(datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z'))  <-- These are the lines that fail
           q.chain('and').on_attribute('end').equals(datetime.strptime(str(obj.end_date) ,'%Y-%m-%d %H:%M:%S%z')) <-- These are the lines that fail
           k8 = calendar.get_events(query=q, include_recurring = True) 

追溯

ValueError at /eventscalendar/event_request_non_approval_view/49
time data '2020-10-31 14:00:18-04:00' does not match format '%Y-%m-%d %H:%M:%S%z'

【问题讨论】:

  • 问题是这个-04:00 和这个%z%z 正在寻找 -0400,没有冒号。我对 Python 中日期/日期时间的解决方案是 dateutil。所以parse('2020-10-31 14:00:18-04:00') datetime.datetime(2020, 10, 31, 14, 0, 18, tzinfo=tzoffset(None, -14400))
  • 所以我尝试了你的建议。这是更新的代码。
  • 不,你没有。我建议使用dateutil。你使用了datetime。您没有导入导致错误的tzoffset
  • 另外,为什么要将日期时间转换为字符串,然后再转换回日期时间?
  • 所以我使用了 Pypl 的 O365 插件。它通过 microsoft graph API 发送查询。我尝试将其保留为日期格式,但日期格式不正确时出现错误

标签: python django postgresql django-views


【解决方案1】:

尝试使用to_timestamp 函数将您的自定义格式转换为PostgreSQL,例如

SELECT to_timestamp('2020-11-01 19:16:59:835', 'YYYY-MM-DD HH24:MI:SS:MS')

详情:https://www.postgresql.org/docs/13/functions-formatting.html

【讨论】:

  • to_timestamp,这可以在 django 和 python scnario 中使用吗?这就是我的项目的基础。
猜你喜欢
  • 2017-12-09
  • 1970-01-01
  • 2021-12-05
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多