Skip to content

Redo timestamp handling #3947

Closed

Description

@roji

The below is an attempt at a fresh look at Npgsql's date/time handling - especially around timestamptz; this has been a problematic point for a long while.

The current situation

  • When reading timestamptz, we currently return a local DateTime, based on the timezone of the local machine where Npgsql is running (similarly, we reading a DateTimeOffset, we return one in the machine's local timezone).
  • This behavior was implement to approximate the PostgreSQL text representation of timestamptz, which is a local timestamp based on the PostgreSQL TimeZone parameter.
    • Npgsql uses the local machine timezone and not the PostgreSQL TimeZone parameter because of the incompatibility between .NET's Windows timezone codes and the PostgreSQL IANA/Olson timezone codes. .NET 6 has added support for the latter, see Read DateTimeOffset with the PostgreSQL TIMEZONE #3594.
    • The NodaTime plugin does use the PostgreSQL TimeZone parameter, since NodaTime has always handled IANA/Olson timezones.

The problem

  • The real meaning/use of timestamptz is to store a timestamp that is known to be in UTC (or rather, "a point in time that can be globally agreed-upon" regardless of timezone). This is in contrast to timestamp without time zone, which stores a date and time in an unknown/unspecified timezone. In that sense they correspond to NodaTime's Instant and LocalDateTime types, or to the BCL's DateTimeKind.Utc and DateTimeKind.Local. The PostgreSQL textual conversion to a local timestamp seems to be a somewhat unfortunate secondary effect.
    • Note that PostgreSQL now() function returns timestamptz, strengthening the idea that timestamptz represents a "point in time".
  • We basically have no way for users to easily store UTC timestamps, and get them back as DateTime(UTC); this most closely matches the recommended UTC-everywhere pattern.
  • You can't easily roundtrip timestamptz, since it gets converted based on your machine's timezone.
  • Since we implicitly convert to/from UTC, it's easy for users to get confused and think values are round-trippable, which they are not; for example, we support writing DateTimeOffset with any offset, although the offset does not get saved in the database.
  • It's currently really hard to work with timestamptz. When writing a DateTime(Utc) to a timestamptz column, we send a timestamp without time zone that gets converted in PostgreSQL, based on the connection TimeZone.
  • We're inconsistent between read and write. For example, reading a timestamptz gives a DateTime(Local), but writing a DateTime(Local) sends a timestamp without time zone.
  • The machine time zone where the .NET application is running is largely irrelevant in most modern applications: a single web server handles requests for users around the world, with many different time zones; the web server's timezone shouldn't matter.
  • Similarly, a database connection state parameter such as TimeZone shouldn't be needed or play a significant role. TimeZone defaults to a PostgreSQL global configuration, which like the .NET machine timezone isn't relevant for most scenarios. The application can change this parameter, but again assuming international, multi-timezone usage, does not seem to be a productive way to program against the database.
  • We've received multiple user complaints about the above, especially that receiving a machine-local DateTime is problematic; the introduction of an additional timezone conversion (from the PG UTC value to the local machine's) is frequently problematic and confusing.
  • The timestamptz PostgreSQL binary representation (as opposed to the text one) is not a local timestamp, but the timestamp as-is (so UTC). A local timestamp may be appropriate when textually interfacing with a database, but not necessarily when writing applications against it.

Possible solutions

We could change Npgsql to no longer return local values for timestamptz:

  • By default, we'd return DateTime(Utc) (with the exact value stored in PG, no conversions), instead of with Kind=Local
  • If the user requests a DateTimeOffset, we'd return one with Offset=0, instead of with a local offset.
  • When using NodaTime, timestamptz would be mapped to Instant, whereas timestamp without time zone would be mapped to LocalDateTime. Reading a timestamptz as ZonedDateTime, OffsetDateTime or DateTimeOffset would produce UTC only (offset=0), never local.

However, things get complicated when we look at writing:

  • Currently, writing DateTime always sends timestamp without time zone (since DateTime(Kind=UTC) being converted to local when inserting to TIMESTAMP WITHOUT TIME ZONE #1803). It would be weird and inconsistent to read timestamptz as DateTime(Utc), but writing DateTime(Utc) as timestamp without time zone. We could revert this and go back to sending timestamptz for DateTime(UTC).
  • We could revert to the previous behavior, where we send timestamptz for DateTime(Utc), and timestamp without time zone otherwise (revert DateTime(Kind=UTC) being converted to local when inserting to TIMESTAMP WITHOUT TIME ZONE #1803)
    • This would bring back DateTime(Kind=UTC) being converted to local when inserting to TIMESTAMP WITHOUT TIME ZONE #1803 was originally filed for: if we send timestamptz for DateTime(Utc) when inserting a DateTime(Utc), then if the user inserts that into a timestamp without time zone column, there would be a conversion.
    • I think the PG behavior here is questionable; applying a timezone conversion when converting from timestamptz to timestamp without time zone treats the latter as a local timestamp, where in fact it really is unspecified.
    • But in any case, this seems like the lesser of the two evils. If you want to store UTC timestamps, use timestamptz. Otherwise, modify the Kind on your DateTime before sending it.
  • Implementation-wise this is annoying, since:
    • This violates our current type handler architecture - a type handler (and therefore PG type) is selected based on a CLR type, not based on the contents of the instance (the Kind).
    • We'd also need to infer for arrays. What do we do with heterogenous arrays of DateTime (some Utc, some Local)? We could check for these in validation and throw.
    • But implementation details shouldn't matter here, but rather desirable behavior.
  • Another theoretical possibility is to map timestamptz to DateTimeOffset; but this doesn't correspond to how people usually want to work with UTC timestamps in .NET.
  • NodaTime doesn't have any issues since the separation is done at the type level: Instant would be written as timestamptz, LocalDateTime as timestamp without time zone.

The breaking changes here are obviously pretty bad - we'd at least have a compatibility switch to go back to the current behavior.

Summary

  • We ideally need one thing that clearly corresponds to timestamptz, and another to timestamp without time zone; this should be consistent across read and write.
  • Unfortunately in .NET, these things are the same CLR type with different kinds: DateTime(Utc) and DateTime(Unspecified/Local). In NodaTime we have two clean types.
  • In the past, we designed around the fact that timestamptz was outputted as a local timestamp in text mode, but we shouldn't let that be the primary thing.

Some history

Related issues

Selected issues where users request we switch to reading UTC, or encounter trouble because of our conversion to local:

Other PG drivers

/cc @vonzshik @NinoFloris @Emill @Brar

Activity

  1. Emill commented on Aug 26, 2021

    @Emill
    Contributor

    From my perspective, timestamptz means "some point in time that can be globally agreed-upon" with no particular time zone attached. If it is stored as utc or some local timestamp with an offset is an implementation detail. In my opinion this maps best to DateTime with Kind=UTC.

    A current user workaround: With the current situation when a user gets back a DateTime with Kind=Local from a timestamptz, it's possible to use ToUniversalTime() to get it as UTC, but that can be quite verbose if the user has to do it everywhere. It is even roundtrippable during a DST change night where you might think it is ambiguous (summer to winter change), since the DateTime struct contains a hidden bit indicating if the time should be treated as before the DST change or after. But it's not roundtrippable if the sysadmin changes the server's time zone after the db call completes and before ToUniversalTime() is called...

    From my perspective, "timestamp without timezone" can either mean a local timestamp or a timestamp with an unspecified time zone. Which of the two it means depends on context. For example PostgreSQL has date/time functions and conversions where the meaning will differ depending on function. For example, casting a "timestamp" to a "timestamptz" assumes the value is in local time and applies the connection's time zone offset to the value and converts it to utc-time. The "at time zone" construct however instructs that the given timestamp is not a local one, but in the specified time zone. It would be better if PostgreSQL would have split "timestamp without time zone" into two types: local time and unspecified time, so yes, PostgreSQL is broken in my opinion. In any case this can map either to DateTime with Kind=Local or to DateTime with Kind=Unspecified, depending on usage. None is more valid than the other in my opinion; it's up to the user how he/she treats the value. One could possibly argue for that Unspecified is a better choice for a general C# db provider, since returning a DateTime with Kind=Local could simply be wrong when using the "at time zone" construct in a query.

    In my opinion a timestamptz should always be mapped as a DateTime with Kind=UTC in both directions. I expect apps that want to use "time points", to get the current time using DateTime.UtcNow and store it as a timestamptz in the db. When reading such a value I as a developer would expect a DateTime with Kind=UTC.

    In my opinion a timestamp without time zone should be mapped as DateTime with Kind=Unspecified.

    When sending a DateTime with Kind=Local to the db however, it gets a bit trickier. In one way, we know that it represents a particular point in time since it has the Local tag and we know the system's time zone, so we could convert it to UTC and send that as a timestamptz to make it represent a "point in time". On the other hand, it might not be what the user expects, since PostgreSQL generally favors "timestamp without time zone" when a we want a local time zone (the "localtimestamp" function returns a "timestamp without time zone" for example). But if the user really wants to represent a point in time, why not just use Kind=UTC instead. So sending Kind=Local is probably best done as a "timestamp without time zone".

    The fact that the "Kind" thing doesn't fit into our type system is not that fun, but it should be our problem and we should deal with it in the best possible way. If for example an array of DateTime values are sent with different Kinds, and the user has otherwise not specified the db type, we should probably throw an error.

    When using DateTimeOffset, it in my opinion doesn't really matter if we use 0 as offset and a utc timestamp, or the offset of the system's or db's time zone.

    I haven't used NodaTime so can't say anything there.

  2. roji commented on Aug 26, 2021

    @roji
    MemberAuthor

    Thanks @Emill - it sounds like we're pretty much in agreement about everything...

    It would be better if PostgreSQL would have split "timestamp without time zone" into two types: local time and unspecified time

    Agreed.

    One could possibly argue for that Unspecified is a better choice for a general C# db provider, since returning a DateTime with Kind=Local could simply be wrong when using the "at time zone" construct in a query.

    Agree there as well - we simply don't know what the actual intent/meaning of the data is, and Unspecified makes less assumptions/assertions about it. This also corresponds with our current behavior of reading timestamp without time zone as DateTime(Unspecified), so less breaking. We'd write either DateTime(Unspecified) or DateTime(Local) as timestamp without time zone - this is effectively the exact behavior we had before #1803 was done in 4.0 (see below for comments on Local).

    In my opinion a timestamptz should always be mapped as a DateTime with Kind=UTC in both directions. I expect apps that want to use "time points", to get the current time using DateTime.UtcNow and store it as a timestamptz in the db. When reading such a value I as a developer would expect a DateTime with Kind=UTC.

    Very much agree - this is the main scenario I have in mind, and seems like the right way to implement "UTC everywhere".

    So sending Kind=Local is probably best done as a "timestamp without time zone".

    Agree as well, and there's one more point to support that... If we write DateTime(Local) as timestamptz by default, then if the user tries to insert that into a timestamp without time zone column they get a conversion on the PG side. I think that would be surprising, and the expectation would be to be able to write DateTime(Local) directly in this scenario.

    Note that there's an additional decision to make - whether we allow writing DateTime(Local) as timestamptz if NpgsqlDbType.TimestampTz is explicitly specified. Doing this would mean doing ToUniversalTime in Npgsql before sending, which is certainly possible; but I'm tempted to disallow this, and arrive at a point where Npgsql never converts timezones, ever - all conversions must be done explicitly by the user.

    There's also the opposite question, of DateTime(Utc) sent with an explicit NpgsqlDbType.Timestamp. We could again just send the value (understanding timestamp as unspecified), or we could even convert to local first (understanding timestamp as local, which I really don't think we should do). Here too, since there are multiple possible options, I'd tend towards disallowing.

    The fact that the "Kind" thing doesn't fit into our type system is not that fun, but it should be our problem and we should deal with it in the best possible way. If for example an array of DateTime values are sent with different Kinds, and the user has otherwise not specified the db type, we should probably throw an error.

    Totally agree, except that we may decide to not support writing DateTime(Utc) as timestamp without time zone, or DateTime(Unspecified/Local) as timestamptz (this is the point just above). In that case we'd throw for any heterogeneous array except for Unspecified/Local.

    When using DateTimeOffset, it in my opinion doesn't really matter if we use 0 as offset and a utc timestamp, or the offset of the system's or db's time zone.

    I do think it's important to remove any dependency on the system's and DB's time zone, and always return Offset=0 when reading. Writing seems a bit trickier - we could convert to UTC beforehand, but that's very similar to allowing DateTime(Local) to be written as timestamptz; I also think it's important to educate users early that timestamptz does not actually store an offset in the database (common understandable misconception), so throwing for any DateTimeOffset where Offset != 0 would help with this. In general, I'm arguing for tightening the type mapping system and making Npgsql more strict.

    Re timestamp without time zone, I don't think DateTimeOffset should be supported in any way (as today).

  3. roji commented on Aug 26, 2021

    @roji
    MemberAuthor

    I haven't used NodaTime so can't say anything there.

    Give it a try one day, I'm sure you'll like it 😉

  4. Emill commented on Aug 26, 2021

    @Emill
    Contributor

    Note that there's an additional decision to make - whether we allow writing DateTime(Local) as timestamptz if NpgsqlDbType.TimestampTz is explicitly specified. Doing this would mean doing ToUniversalTime in Npgsql before sending, which is certainly possible; but I'm tempted to disallow this, and arrive at a point where Npgsql never converts timezones, ever - all conversions must be done explicitly by the user.

    In this case it would make most sense to do an internal ToUniversalTime() in Npgsql. To send it as is (i.e. as utc) would be wrong, since when the user then opens the db tool and sees the text representation of it, the time point will not represent the correct one. When we have Kind=Local from the user, it's assumed the time zone for this DateTime is the system's current one, so it will never be wrong to convert it to UTC using ToUniversalTime(). If we see the timestamptz type as a "point in time", as described earlier, it doesn't matter if the internal representation is a utc timestamp only or some local time with an offset tag (both can represent the same time point). And it happens so that PostgreSQL's internal format uses the former while its text format uses the latter.

    There's also the opposite question, of DateTime(Utc) sent with an explicit NpgsqlDbType.Timestamp. We could again just send the value (understanding timestamp as unspecified), or we could even convert to local first (understanding timestamp as local, which I really don't think we should do). Here too, since there are multiple possible options, I'd tend towards disallowing.

    I don't know but there might be people that have set up their database to use "timestamp without time zone" and store utc time stamps in it. There is no "ToUnspecified()" method for DateTime, so it might be hard to correctly store the value for them. I don't know if we should try to solve this or just disallow it...

    Re timestamp without time zone, I don't think DateTimeOffset should be supported in any way (as today).

    Yeah the type doesn't fit at all into PostgreSQL's type system. At the same time when using DateTime offset, it's clear at least what point in time it represents when you for example print it. When using ToString() on a DateTime for example, we don't know its Kind. So I'm not sure.

  5. roji commented on Aug 26, 2021

    @roji
    MemberAuthor

    There is no "ToUnspecified()" method for DateTime, so it might be hard to correctly store the value for them. I don't know if we should try to solve this or just disallow it

    I think here users can use DateTime.SpecifyKind.

    For both here and for Kind=Local, I'm hovering between allowing and disallowing (i.e. throwing). I think in the long term it may be better for everyone if we adopt a stricter mapping here, where users must think about what it is they're storing, etc. I also think there's considerable simplicity in being able to say "Npgsql never ever does timezone conversion on your values".

  6. self-assigned this
    on Aug 26, 2021
  7. added this to the 6.0.0 milestone on Aug 26, 2021
  8. added a commit that references this issue on Aug 28, 2021
    700260a
  9. roji commented on Aug 29, 2021

    @roji
    MemberAuthor

    Note: with the pretty massive changes being done here, we really should make a decision on #2009 as well for 6.0.

  10. changed the title [-]Looking at our date/time handling... again.[/-] [+]Redo timestamp handling[/+] on Aug 29, 2021
  11. RomainHautefeuille commented on Sep 9, 2021

    @RomainHautefeuille

    I would like to share my experience as a user on this topic:
    We currently are using DateTime with Kind=Utc as source in our entities along with timestamp without tz columns on postgresql.
    Thus we are reading back a DateTime with Kind=Unspecified and we need to manually change the Kind back to Utc somewhere after loading our entities.

    Back then, I tried a commit to let users configure the default Kind to use for timestamp without timezone reading at a global level, if you are interested: RomainHautefeuille@e96b3ab
    (The way it worked was to let the user override the factory, to return a handler that has a different default Kind when reading, i.e. Utc)
    I can see factories have been removed in #3956 so my commit is now probably obsolete though. I also prbably overlooked many aspects in my naive approach.

    Anyway, I am really interested in the resolution of this issue, looking forward to it.

  12. Clockwork-Muse commented on Sep 11, 2021

    @Clockwork-Muse

    This is in contrast to timestamp without time zone, which stores a date and time in an unknown/unspecified timezone. In that sense they correspond to NodaTime's Instant and LocalDateTime types, or to the BCL's DateTimeKind.Utc and DateTimeKind.Local.

    This is incorrect. It better corresponds to DateTimeKind.Unspecified, because DateTimeKind.Local has a known/discoverable timezone - that of the current process.
    NodaTime's LocalDateTime doesn't mean "local to the machine/process" - it means "local to an unspecified reference".

    PostgreSQL does you no favors here, because it doesn't persist the offset of the original timestamp (which can be useful information).

  13. roji commented on Sep 11, 2021

    @roji
    MemberAuthor

    @Clockwork-Muse PG's timestamp without time zone sometimes functions more like DateTimeKind.Unspecified, and sometimes like DateTimeKind.Local. For example, when you cast a timestamp with time zone to a timestamp without time zone, PG implicitly performs timezone conversion using the connection's TimeZone parameter, which represents the "local" time zone; in that sense timestamp without time zone functions as a local timestamp, rather than as an unspecified one. I personally think that this ambiguity between local and unspecified in PostgreSQL is problematic, but it is what it is.

    In any case, this particular question doesn't seem to have much actual impact on the design decisions above, as far as I can see; the main point is to map DateTimeKind.Utc to timestamp with time zone, and the Local/Unspecified ones to timestamp without time zone. Do you see an issue here, or think things should be different in some way?

    PS You can read more on this in @Emill's comment above

  14. Clockwork-Muse commented on Sep 12, 2021

    @Clockwork-Muse

    I don't think I see a problem with the mapping, no.

    (I see problems with types, or lack of types, especially on the PostgreSQL side, but that's not something that can be dealt with here)

    Although note that DateTimeKind.Unspecified is treated as DateTimeKind.Local for ToUniversal() (and as DateTimeKind.Utc for ToLocal().

    Re timestamp without time zone, I don't think DateTimeOffset should be supported in any way (as today).

    Yeah the type doesn't fit at all into PostgreSQL's type system. At the same time when using DateTime offset, it's clear at least what point in time it represents when you for example print it. When using ToString() on a DateTime for example, we don't know its Kind. So I'm not sure.

    This though... I'd really want DateTimeOffset to be supported, although there are problems with the offset disappearing, and either getting back the equivalent UTC time (for timestamp with time zone), or local-only time (for timestamp without time zone). You'd have to store an additional field, which could at least be done by the application with some sort of custom mapper (which I assume is supported), but might not be something you could have the driver do itself.

  15. roji commented on Sep 12, 2021

    @roji
    MemberAuthor

    Although note that DateTimeKind.Unspecified is treated as DateTimeKind.Local for ToUniversal() (and as DateTimeKind.Utc for ToLocal().

    Yep, that's similar to the PostgreSQL behavior, but I'd argue that it muddles the Unspecified/Local distinction in .NET DateTime just like PG muddles it a bit with timestamp without time zone. Either way, this seems to be more of a terminological/theoretical discussion than something that would impact Npgsql mappings etc.

    I'd really want DateTimeOffset to be supported, although there are problems with the offset disappearing, and either getting back the equivalent UTC time (for timestamp with time zone), or local-only time (for timestamp without time zone). You'd have to store an additional field, which could at least be done by the application with some sort of custom mapper (which I assume is supported), but might not be something you could have the driver do itself.

    I understand (and agree with most of the above), but it's worth noting that DateTimeOffset is also a problematic concept - it encourages the idea that an offset is a sufficient representation of a timezone, which isn't at all the case - a true timezone (e.g. Europe/Berlin) also includes daylight savings information, which means different offsets in different parts of the year (compare the NodaTime ZonedDateTime and OffsetDateTime types). In that sense, I think the PG type system does do a better job than SQL Server, since the latter does support storing a full DateTimeOffset in the database, providing a possibly dangerous illusion of time zones being dealt with.

    More concretely... the direction we're going in is to allow writing DateTimeOffset to PG, but only if the offset is 0 (i.e. Npgsql will throw for non-zero offsets). This both restricts to values that can be round-tripped without data loss, and ensures no timezone conversion is performed by the driver (these are two basic principles behind then new date/time mapping system being done here).

  16. added a commit that references this issue on Sep 13, 2021
    a579c17
  17. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions