python 2.7 中尝试将日期时间转换为 unix 时间戳时出现属性错误
attribute error while trying to convert datetime to unix timestamp in python 2.7
我正在查询数据库以获取日期时间,然后尝试将其转换为 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
我测试了一些东西和 dt
类型 DateTimeType
传递给 toUnix()
函数时。此外,当我将 dt.timetuple()
替换为 datetime.now().timetuple()
时,它会打印出预期的结果。我也尝试过不替换 tzinfo,而是给出 AttributeError: timetuple
。如果是日期时间,为什么会出现这个错误?
您假设 sel
将是一个日期时间对象,但事实并非如此。不可能从您发布的代码片段中得出它,并且很可能作为字符串返回(取决于数据库客户端)。这样做的一般形式是
dt = datetime.strptime(sel[0][0], '%b %d %Y %I:%M%p')
其中 %b %d %Y %I:%M%p
是字符串的格式。
编辑:格式化
我正在查询数据库以获取日期时间,然后尝试将其转换为 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
我测试了一些东西和 dt
类型 DateTimeType
传递给 toUnix()
函数时。此外,当我将 dt.timetuple()
替换为 datetime.now().timetuple()
时,它会打印出预期的结果。我也尝试过不替换 tzinfo,而是给出 AttributeError: timetuple
。如果是日期时间,为什么会出现这个错误?
您假设 sel
将是一个日期时间对象,但事实并非如此。不可能从您发布的代码片段中得出它,并且很可能作为字符串返回(取决于数据库客户端)。这样做的一般形式是
dt = datetime.strptime(sel[0][0], '%b %d %Y %I:%M%p')
其中 %b %d %Y %I:%M%p
是字符串的格式。
编辑:格式化