set the whole interpreter as UTC in python

Viewed 1189

I want to make sure that a whole script is using by default only UTC. Any idea how to do that? I have been looking for solutions, but somehow not found anything working. Really all what I want is to make sure that:

import datetime
# SOME CODE HERE
print(datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S'))

Does print 1970-01-01 00:00:00, on any machine, without more trouble, and that everything is treated as UTC.

3 Answers

If you ensure that the environment variable TZ is set before importing datetime, then it is not necessary to use time.tzset().

For example:

>>> import os
>>> os.environ["TZ"] = "UTC"
>>> import datetime
>>> print(datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S'))
1970-01-01 01:00:00

In order to avoid editing your Python script, you can just set the environment variable when executing it. For example in the Linux command line:

env TZ=UTC python myscript.py

You can use a convenience function from datetime that was literally designed for this purpose, without the need to set up a timezone through other libraries:

from datetime import datetime
# SOME CODE HERE
print(datetime.utcfromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S'))
# '1970-01-01 00:00:00'

However, if you would also need to have this UTC zone in other uses, say, third-party libraries, etc., then the solution with tzset() is probably more convenient :)

I think this should work:

import datetime
import time
import os

os.environ["TZ"] = "UTC"
time.tzset()

print(datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S'))
Related