尝试在 Python 2.7 中将日期时间转换为 Unix 时间戳时出现属性错误



>我正在查询数据库以获取日期时间,然后尝试将其转换为 unix 时间戳。这是我的一些代码:

#! /bin/python
import time, pytz
from datetime import datetime
eastern = pytz.timezone("US/Eastern")
def toUnix(dt):
#converts a datetime to a unix timestamp
return time.mktime(dt.timetuple())
def getFillStartTime(fillNo):
#returns the start time of a fill as a unix time stamp
dsacursor.execute('select startTime from fillInfo where fillNo = @fillNo',{'@fillNo':fillNo})
sel = dsacursor.fetchall()
dt = sel[0][0]
dt = dt.replace(tzinfo = eastern)
return toUnix(dt)
print getFillStartTime(20318)

当我运行它时,我得到AttributeError: replace这是回溯:

Traceback (most recent call last):
File "test.py", line 27, in <module>
print getFillStartTime(20318)
File "importToLogView.py", line 25, in getFillStartTime
dt = dt.replace(tzinfo = eastern)
AttributeError: replace

我已经测试了一些东西,并在传递给toUnix()函数时DateTimeType类型dt。此外,当我用datetime.now().timetuple()替换dt.timetuple()时,它会打印预期的结果。我也尝试不更换 tzinfo,而是提供AttributeError: timetuple。如果是日期时间,为什么会发生此错误?

你假设sel将是一个日期时间对象,但事实并非如此。不可能从您发布的代码片段中得出它,并且很可能以字符串形式返回(取决于数据库客户端(。这样做的一般形式是

dt = datetime.strptime(sel[0][0], '%b %d %Y %I:%M%p')

其中%b %d %Y %I:%M%p是字符串的格式。

编辑:格式化

最新更新