0

In my app users provide their timezone and saved.

So I handle timezone conversion manually

    local_time = datetime.now(tz=ZoneInfo(self.time_zone))
      #time_zone is "US/Pacific"

Yet still when I save into postgres it is converted back to UTC 0.

In the settings:

    # TIME_ZONE = 'UTC' #commented out
    USE_L10N = False
    USE_TZ = False

That too did not work, so I made a middleware:

    # CUSTOM TIME ZONE HANDLER
    class TimezoneMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response

        def __call__(self, request):
            time_zone = "US/Pacific" #will be changed to a fn call
            if time_zone:
                timezone.activate(pytz.timezone(time_zone))
            else:
                timezone.deactivate()
            return self.get_response(request)

In settings:

    MIDDLEWARE = [
        ...
        'time_log_app.utils.TimezoneMiddleware',
    ]

This is the function that inserts the data:

    def insert_data_time_log(user, data):
       #this is the data obj before insertion

    {
    'clock_out': datetime.datetime(2021, 8, 21, 8, 16, 30, 420947, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific')), 
    'hourly_rate': 50
    }
        ...
        TimeLog.objects.create(pk=user, **data)

The model:

    class TimeLog(models.Model):
        clock_in = models.DateTimeField(null=True, blank=True)
        clock_out = models.DateTimeField(null=True, blank=True)
        hourly_rate = models.DecimalField(max_digits=20, decimal_places=2, null=True)
        employee_type = models.CharField(max_length=200, null=True)

That too is not working!!

I'm pretty much out of hope here, what I'm doing wrong??

Or I should use raw sql for this?

Here is the screenshot of postgres enter image description here

11
  • you haven't shown any code which interacts with PostgreSQL. Is this about PostgreSQL at all? And the python you do show, it is not clear what context it should be in. "AttributeError: module 'datetime' has no attribute 'now'" Commented Aug 21, 2021 at 15:30
  • @jjanes. from datetime import datetime datetime.now() datetime.datetime(2021, 8, 21, 8, 45, 17, 189704) Commented Aug 21, 2021 at 15:46
  • I just edit in the function that interacts with PostgreSQL Commented Aug 21, 2021 at 15:47
  • Except that left out the important parts which are 1) What is data? 2) What happens in ...? Commented Aug 21, 2021 at 15:48
  • Add data object too Commented Aug 21, 2021 at 15:52

1 Answer 1

3

PostgreSQL always stores timestamptz in UTC, but converts them to your session timezone when it sends them back to you (and when it receives them from you, it interprets them as being in your session timezone if they lack an explicit timezone). If you want to see them in a different timezone than your session timezone, you can change your session timezone set timezone='US/Pacific' or you can convert it using python once it comes back.

If you declare them to be 'timestamp without time zone' in the database, then it will no longer convert them on the way in or out.

Sign up to request clarification or add additional context in comments.

3 Comments

I already converted them. So how do I stop postgres from converting them?
See my comments in the discussion. The short version, you can't.
@jjanes please do not recommend timestamp, that will result in an un-anchored timestamp that is returned with no offset. If the user changes their self.time_zone then the displayed values will be wrong. Or if @FieldBoy attempts to cast them to timestamptz they will be rotated to whatever the value of show time is. The only way you have a hope of making that work is adding a column that stores the time zone for the timestamp. Then you have to be extremely diligent about making sure that stays correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.