[英]attribute error while trying to convert datetime to unix timestamp in python 2.7
I'm querying a database to get a datetime and then trying to convert it to a unix timestamp. 我正在查询数据库以获取日期时间,然后尝试将其转换为UNIX时间戳。 Here is some of my code: 这是我的一些代码:
#! /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)
When I run it I'm getting AttributeError: replace
here is the traceback: 当我运行它时,我得到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
I have tested some things and dt
of type DateTimeType
when it is passed to the toUnix()
function. 当它传递给toUnix()
函数时,我已经测试了一些东西和类型为DateTimeType
dt
。 Also, when I replace dt.timetuple()
with datetime.now().timetuple()
it prints the expected result. 另外,当我用datetime.now().timetuple()
替换dt.timetuple()
,它会打印出预期的结果。 I have also tried not replacing the tzinfo and it gives AttributeError: timetuple
instead. 我也尝试过不替换tzinfo,而是使用AttributeError: timetuple
代替。 If it is a datetime, why is this error occurring? 如果是日期时间,为什么会发生此错误?
You're assuming that sel
will be a datetime object, but it's not. 您假设sel
将是日期时间对象,但事实并非如此。 It's not possible to derive that from the code snippet you have posted, and most likely is being returned as a string (database client depending). 不可能从您发布的代码片段中得出,并且很可能以字符串形式返回(取决于数据库客户端)。 The general form for doing so is 这样做的一般形式是
dt = datetime.strptime(sel[0][0], '%b %d %Y %I:%M%p')
where %b %d %Y %I:%M%p
is the format of the string. 其中%b %d %Y %I:%M%p
是字符串的格式。
EDIT: formatting 编辑:格式化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.