Time Zone issues

Hi folks,

Anvil actually takes extreme care with Python datetime objects, because dealing with timezones is such a minefield. Here’s how it works:

  • Any timezone-aware datetime object retains its timezone when transferred in any direction between client, server and Data Tables.
  • Any naïve datetime object that is transferred between client and server gets automatically ‘stamped’ with the timezone of the place where it was created before it is transferred. This means that datetime objects generated on the client get the timezone of the browser, while those generated on the server are stamped with the timezone of the server, which is always guaranteed to be UTC (not UK time, which is different in the summer).

These deceptively simple rules mean that you can always compare datetime objects, no matter where they were created and no matter how much you’ve moved them around or stored them in the DB.

You can explictly create timezone-aware datetime objects if you wish, using helper classes from the anvil.tz module:

import anvil.tz

naive_local = datetime.now()
aware_local = datetime.now(anvil.tz.tzlocal())

naive_utc = datetime.utcnow()
aware_utc = datetime.now(anvil.tz.tzutc())   # note: NOT datetime.utcnow()
  
aware_custom = datetime(2017,11,16,23,45,15,0, anvil.tz.tzoffset(hours=3))

print "Naive local: %s" % naive_local
print "Aware local: %s" % aware_local

print "Naive UTC: %s" % naive_utc
print "Aware UTC: %s" % aware_utc

print "Aware custom: %s" % aware_custom

I hope that helps!

10 Likes