Pickels
Pickels

Reputation: 34660

Custom utc now date function returns same result

Code:

def setup_function(function):
    db.query('''
    CREATE OR REPLACE FUNCTION now_utc() RETURNS timestamp as $$
      select now() at time zone 'utc';
    $$ language sql;
    ''')

def teardown_function(function):
    db.query('DROP FUNCTION now_utc();')

def test_one ():
    print datetime.datetime.utcnow(), db.query('select now_utc();')[0]
    time.sleep(5)
    print datetime.datetime.utcnow(), db.query('select now_utc();')[0]

def test_two ():
    print datetime.datetime.utcnow(), db.query('select now_utc();')[0]
    time.sleep(5)
    print datetime.datetime.utcnow(), db.query('select now_utc();')[0]

Results:

test_one:
2017-02-28 15:51:19.962640 <Record {"now_utc": "2017-02-28T15:51:19.962945" }>
2017-02-28 15:51:24.974434 <Record {"now_utc": "2017-02-28T15:51:19.962945" }>

test_two:
2017-02-28 15:51:24.999673 <Record {"now_utc": "2017-02-28T15:51:25.000101" }>
2017-02-28 15:51:30.007059 <Record {"now_utc": "2017-02-28T15:51:25.000101" }>

Problem:

I am using Records which is a thin layer on top of alchemy. The problem I am having is that now_utc returns the same datetime within each test.

Upvotes: 0

Views: 69

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51599

Please use clock_timestamp() instead of now() - now() is a time of transaction start, not statement. Docs:

now() Current date and time (start of current transaction)

clock_timestamp() timestamp with time zone Current date and time (changes during statement execution);

Upvotes: 1

Related Questions