Handling dates and times in SQL queries with PostgreSQL

(mon-code.net)

28 points | by metfan 3 days ago

6 comments

  • heyitsdaad 24 minutes ago
    I am not a fan of performing non database operations in databases. Date and timezone is one of those. My rule is DB always uses epoch seconds. Caller manages date conversions.
    • masklinn 10 minutes ago
      > My rule is DB always uses epoch seconds.

      Does your rule also say to never do calendaring / store future events in a database?

      Because if it does not, it’s deeply and irredeemably broken.

    • Horffupolde 10 minutes ago
      Have fun.
  • flossly 4 hours ago
    Lame article tbh.

    It's better to use `timestampz` everywhere; the author seems to know but then uses `timestamp`...

    Most of the functions showcased one will not need as one will do that in the app-layer or even in the frontend code.

    • happytoexplain 48 minutes ago
      Calendar/clock components are not guaranteed to survive round trip conversion to another time zone, including UTC.
    • masklinn 1 hour ago
      > It's better to use `timestampz` everywhere

      Incorrect, that is completely broken for any future event.

      > the author seems to know but then uses `timestamp`...

      The author also explains clearly why they do so:

      > I use timestamp in this article so that results do not depend on the session time zone

      • dathinab 1 hour ago
        > Incorrect, that is completely broken for any future event.

        so is usage of `timestamp`, except that is _even more broken_

        what you need is a `timestamp with timezone` which actually keeps the timezone instead of converting to UTC

        and `timestamp`+some timezone column do not quite do that correctly

        to put it simple for "calendaric correct"/"even planing" usage all of the pg (and in general SQL) build in types are largely inadequate

        in the end for a lot of non-calender/event usage storing everything in UTC and returning it as UTC timestamp or date time string with time zone is preferable. You then can convert them to whatever timezone the user has set in their frontend _in that frontend_.

        > The author also explains clearly why they do so:

        and at the same time run into way worse things like timezone information in datetime strings being silently ignored and in turn your datetime stamps moving timezone "accidentally"

        only with timestamptz do you get somewhat correct datetime string parsing, sure it might "display" the datetime in the session locality (which IMHO is dump) but it does so _with_ timezone offset information. So its still the correct time no matter the session locality. And you anyway have to parse/convert it to local time in the frontend of the user as that timezone can be arbitrarily different.

        • FrancoisBosun 26 minutes ago
          I'm responding to your claim "which actually keeps the timezone instead of converting to UTC".

          From https://www.postgresql.org/docs/current/datatype-datetime.ht...

          > For timestamp with time zone values, an input string that includes an explicit time zone will be converted to UTC (Universal Coordinated Time) using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone.

          > timestamptz is accepted as an abbreviation for timestamp with time zone; this is a PostgreSQL extension.

          Even if you do `INSERT INTO foo(created_at) VALUES ('2026-12-06T10:37-05')`, the stored value will be `2026-12-06T15:37+00`.

          This is by design.

          If you `SET timezone TO '...'`, `timestamptz` columns will be converted on output (and on input if they lack the `+` or `-` TZ offset markers).

          • masklinn 12 minutes ago
            > This is by design.

            They never said otherwise. Being shit can be by design.

        • masklinn 13 minutes ago
          > so is usage of `timestamp`

          You might want to notice I never said timestamp was adequate.

    • LittleLily 3 hours ago
      Given that most people will be doing most of the time functions in their application code anyway like you said, why would it not be better to just use `timestamp` everywhere then? They both store the same data and the only difference is that `timestamptz` adds an unnecessary conversion on read and write operations (which also changes based on the system's timezone) that you should be doing in your application anyway.
      • epgui 3 hours ago
        Your data at rest is meaningless unless it represents a point in time. You can’t generally compare timestamps or filter by > or < or do any date arithmetic, unless you have points in time or other implicit guarantees (eg.: all of the timestamps are relative to the same time zone, there is no DST, and no historical time adjustments).

        When you get into the weeds, it’s almost impossible to correctly use.

        • LittleLily 3 hours ago
          but `timestamptz` doesn't solve that. it doesn't store a timezone for you. it's still on you to turn the raw timestamp into an actual point in time by enhancing it with timezone/offset data, it's just a question of whether you rely on that extra data coming from your system's configured timezone (which is what `timestamptz` does every time you read the value), or something your application decides.
          • masklinn 1 hour ago
            As the article notes it actually only stores points in time (instants). Which is the issue when you want a civil time instead, especially in the future (events).
      • n_e 2 hours ago
        Some reasons would be to document what is stored in the column and make it convenient to do interactive queries.

        Otherwise we could go even further than timestamp and store the unix time in a bigint column.

        • masklinn 1 hour ago
          …

          That’s what timestamptz does already.

  • ruslanty 3 days ago
    For reports by local date, I’d convert both local midnights to timestamptz separately, then filter with ts >= start AND ts < end. If you take the first midnight and just add 24 hours, you can miss an hour or pull in an hour from the next day when the clocks change
  • traceroute66 4 hours ago
    Interesting site, but its missing some of the more advanced things you can do in Postgres like `EXCLUDE USING gist` to prevent overlapping schedules.
  • luca_ardito_b 1 hour ago
    do ppl actually switch to clock_timestamp() for created_at in long batch jobs, or is now() fine there
  • dathinab 1 hour ago
    Never use timestamp(no tz).

    You servers or pg session locality should not affect the datetimes you handle or their arithmetic, that this even exist can be seen as historic legacy and anti-pattern we now know better.

    If you just display timestamps you can

    1) store them in UTC (timestamptz) and send datetime string with timestamp or utc

    3) return it as utc or with explicit timezone/offset, never rely on implicit time zones it's a food gun

    2) convert it in the frontend to the timezone the frontend is in (which often isn't the same timezone as the one your pg session/servers/etc are in)

    But if you do international cross timezone handline and want it perfectly correct you are in in a world of pain and have to:

    1) record the _locality_ (not time zone) for which the time is relevant (places change timezone assignments, if that happens you need handle it "somehow", doing it fully correctly is huge pain I will omit)

    2) record the timezone for that locality, which is distinct from the users TZ, servers TZ, session TZ, etc. (outside of maybe audit log _nothing_ should depend on the servers or pg sessions TZ)

    3) make sure you did record the timezone, and not the offset, it's not the same

    4) record the datetime in that timezone timezone

    5) record the datetime as datum(y,m,d)+time, _not_ as unix offset (offset->datetime mapping can change)

    6) arithmetic done on such a time should most times be done in that timezone, except bunch of situation you might need to do it in the frontends timezone and/or utc/company time zone etc. (and needs to use a timezone & location aware computation)

    7) some forms of arithmetic _needs to consider cultural aspects_ , physical location+lang settings aren't enough, POSIX locality setting can theoretically handle it, but practically doesn't, so have fun :/ Especially given that sometimes you need the cultural aspects of _where_ the event/timestamp is in the world and sometimes it depends on _who_ requests the arithmetic :(

    to just scratch the surface, practically even most larger calendar apps will _not_ do this perfectly, and often doing it 90% correct is way less work and "good enough". Still even that 90% need all the points above..., just in simpler form

    E.g. daylight saving time makes days have !=24h _in some places and and different times a year_, countries & areas in them change time zones and or iff there is daylight saving time. Areas in a country which have one time zone don't always change all at one and areas also sometimes change which country they are in. Weeks don't always start on Monday, or Sunday. Timezone+language setting does not at all determine when on which day the week starts, or which date time format people find acceptable. You also can't rely on changes in timezones/offset happening at midnight, e.g. daylight saving e.g. tends to switch at 2am. Also don't let people input 12pm/am, weather 12pm is midnight or noon changes depending on culture, worse some places (US Publishing Office 2000vs.2008) have over time changed what it is supposed to mean...

    • masklinn 6 minutes ago
      > Never use timestamp(no tz).

      > You servers or pg session locality should not affect the datetimes you handle or their arithmetic

      These are incompatible statements. Converting between the connection-local timezone and utc is more or less the only thing timestamptz does compared to timestamp.