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?

3
  • Possible duplicate of Converting to unix timestamp Python Commented Jul 31, 2017 at 15:44
  • What is the output if you put print type(dt) after dt = sel[0][0]? Commented Jul 31, 2017 at 15:45
  • <type 'DateTimeType'> Commented Jul 31, 2017 at 15:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

if I print type(dt) after dt = sel[0][0] the output is <type 'DateTimeType'>
Yes, I would assume so, because your database client is most likely casting that. Python datetime (and pytz) doesn't understand that, so you'll need to get it into <type 'datetime.datetime'> or something similar. Also, what database client are you using?
Thanks, that fixed it. I'm using Sybase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.