如何阻止python将mySQL日期时间转换为日期时间.日期什么时候是00:00:00?

2024-05-15 04:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从mySQL数据库读取各种数据类型。数据库中第五列的类型为“DATETIME”。我用它作为“血迹追踪”对象的输入日期。在

import mysql.connector
from datetime import timedelta
from datetime import datetime

show_DB = """select  RUID, test_sname, test_value, units, ref_range, entry_date from %s
             where RUID=%%s and test_sname=%%s order by RUID,
             test_sname, entry_date Limit 5;""" % (tableToUse,)

cursor.execute(show_DB, (ruid, traitPair[0]))
resultsForOneTrait = cursor.fetchall()

for result in resultsForOneTrait:
    ruid = result[0]
    s_name = result[1].decode("UTF-8")
    value = result[2]
    units = result[3].decode("UTF-8")
    ref_range = result[4].decode("UTF-8")

    # Need assistance here
    entryDate = result[5]

    record = BloodTraitRecord(ruid, s_name, value, units, ref_range, entryDate)

血迹追踪类:

^{pr2}$

数据库中的DATETIME对象在mySQL服务器中如下所示:

'2008-11-14 13:28:00'

除非数据库中的时间是午夜,否则代码将按预期工作,如下所示:

'2014-05-18 00:00:00'

在这种情况下,也只有在这种情况下,我在比较记录的条目时会得到这个错误_日期.日期()另一个日期时间.日期在代码后面:

# 'cancerCutoff' is consistently a datetime.date 
cancerCutoff = firstCancerAnemiaCodeDate[ruidkey] - timedelta(days=180)
if cancerCutoff < record.entry_date.date():
AttributeError: 'datetime.date' object has no attribute 'date'

印刷记录条目日期确认此案例的时间属性已消失:

'2014-05-18'

我有一种方法来解决这个问题,方法是检查对象的类型,如果对象是datetime,则只调用date属性,但是我想知道是否有比这更好的修复方法。在

我也不明白为什么python会立即将MySQL DATETIME转换为日期时间.日期当DATETIME时间为00:00:00时。在

谢谢你的帮助!在


Tags: 对象fromtestimportref数据库datetimedate
1条回答
网友
1楼 · 发布于 2024-05-15 04:08:58

我将确保您在从数据库中提取datetime对象后立即拥有它。那你以后就不用做任何检查了。所以你可以说:

entryDate = ensure_datetime(result[5])

这只是一点额外的代码,而且还有一个优点:如果您的查询发生更改,而您没有在代码之后正确地更新代码,那么它将立即捕获类型错误。下面是一个实现示例:

^{pr2}$

演示:

for x in [date(2016, 5, 12),
          datetime(2016, 5, 12, 9, 32, 57, 345),
          'a string']:
    print(ensure_datetime(x))

输出:

2016-05-12 00:00:00
2016-05-12 09:32:57.000345
Traceback (most recent call last):
  File "/Users/alexhall/Dropbox/python/sandbox/sandbox.py", line 14, in <module>
    print(ensure_datetime(x))
  File "/Users/alexhall/Dropbox/python/sandbox/sandbox.py", line 9, in ensure_datetime
    raise TypeError('%s is neither a date nor a datetime' % d)
TypeError: a string is neither a date nor a datetime

但我觉得你不想这么做,所以我会用下面的方式来美化它:

def clean_types(row):
    new_row = []
    for item in row:
        if isinstance(item, date) and not isinstance(item, datetime):
            item = date_to_datetime(item)
        elif isinstance(item, str):
            item = item.decode("UTF-8")
        new_row.append(item)
    return new_row

# Demo
print(clean_types([3, 'abc', u'def', date.today(), datetime.now()]))
# [3, u'abc', u'def', datetime.datetime(2016, 5, 12, 0, 0), datetime.datetime(2016, 5, 12, 17, 22, 7, 519604)]

现在您的代码可以缩短为:

for result in resultsForOneTrait:
    record = BloodTraitRecord(*clean_types(result))

你不必记得做任何事。在

相关问题 更多 >

    热门问题