0

I'm querying a database to get a datetime and then trying to convert it to a unix timestamp. 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:

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. Also, when I replace dt.timetuple() with datetime.now().timetuple() it prints the expected result. I have also tried not replacing the tzinfo and it gives AttributeError: timetuple instead. If it is a datetime, why is this error occurring?

Mike Delmonaco
  • 314
  • 4
  • 13

1 Answers1

0

You're assuming that sel will be a datetime object, but it's not. 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.

EDIT: formatting

Andrew Sledge
  • 10,163
  • 2
  • 29
  • 30