Checking if date is in UTC format

Question:

Im using the pytz module to translate a date in America/Los_Angeles timezone to utc by the code below :

TZ = 'America/Los_Angeles'
from = pytz.timezone(TZ)
utc = from.localize(original_date).astimezone(pytz.utc)

Now,i want to test if utc value is actually in UTC format or not. How to do that with pytz or datetime ?

Please Help
Thank You

Asked By: Jill

||

Answers:

utc.tzinfo == pytz.utc # returns True if utc in UTC

Example:

now = datetime.datetime.now(pytz.utc)
now.tzinfo == pytz.utc # returns True

now = now.astimezone(pytz.timezone('America/Los_Angeles'))
now.tzinfo == pytz.utc # returns False
Answered By: eumiro

The accepted answer will not work for anything else as pytz objects. As pytz is actually pretty bad at doing conversions[1] (e.g. properly doing daylight savings etc) it is probably better to do a cross-implementation check.

now = datetime.datetime.now(pytz.utc)
if now.tzinfo:
    now.utcoffset().total_seconds() == 0 # returns true

[1] https://pendulum.eustace.io/blog/a-faster-alternative-to-pyz.html

Answered By: Bolke de Bruin

You can do it simply like this:

from datetime import datetime, timezone
lunch_time = datetime.now(timezone.utc)

if lunch_time.format('%Z') == 'UTC':
     print("Eat food")

This will also work with a naive time object because lunch_time.format('%Z') will return an empty string. This method will also work with pytz or any other module because you are simply checking the timezone as string not as an object (the accepted answer won’t work with the above timezone module case, only pytz).

from datetime import datetime
import pytz
dinner_time = datetime.now(pytz.timezone('UTC'))

if dinner_time.format('%Z') == 'UTC':
     print("Hungry!")

Note: This will also eliminate the possibility of the timezone being GMT timezone rather than UTC timezone. The other answer now.utcoffset().total_seconds() == 0 will be True for GMT which may not be what you want.

The %Z specifier is documented here:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Answered By: theQuestionMan

Similar to a previous answer, you can do it like this:

If you have a given datetime object, you want to first convert it to a string with the strftime() method, then pass in the %Z specifier which gives the timezone name returning one of ‘(empty), UTC, GMT’ according to the documentation.

so an example is:


def check_if_utc(my_datetime):
   return my_datetime.strftime('%Z') == 'UTC'
    
Answered By: Jay 3d
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.