DEV Community

Cover image for Snippet: Change timezone for DateTime object
Peter van der Does
Peter van der Does

Posted on

3 2

Snippet: Change timezone for DateTime object

Information

Convert a Python DateTime object from one timezone to another timezone. This snippet accepts either a naive or aware DateTime object.

Snippet

# code/timezone.py

import datetime as dt
import pytz


def to_timezone(datetime_value, tz):
    """
    Convert the given datetime object to a datetime object with the given timezone.
    Accepts both aware and naive datetime objects

    Parameters
    ----------
    datetime_value: datetime.datetime
    tz: pytz.timezone

    Returns
    -------
    datetime.datetime
    """
    if not isinstance(datetime_value, dt.datetime):
        raise SyntaxError

    if not hasattr(tz, "zone") or tz.zone not in pytz.all_timezones:
        raise SyntaxError

    if (
        datetime_value.tzinfo is not None
        and datetime_value.tzinfo.utcoffset(datetime_value) is not None
    ):
        datetime_value = datetime_value.astimezone(tz)
    else:
        datetime_value = tz.localize(datetime_value)

    return datetime_value

Enter fullscreen mode Exit fullscreen mode

Found a typo?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. Instead of posting a comment, please go directly to GitHub and open a pull request with your changes.


Photo by Ijaz Rafi - https://unsplash.com/photos/L4hg5o67jdw

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay