You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
UTC DateTime is not saved correctly when Postgres server is set to time zone other than UTC #2209
When postgresql.conf has this setting: timezone = 'Europe/Brussels'
(Europe/Brussels is UTC + 1)
This code will save the timestamp 1 hour too early (and exception will be thrown)
vartimestamp=DateTime.UtcNow;using(varcommand=newNpgsqlCommand()){varsql="INSERT INTO testtable (id, timestamp) VALUES (@id, @timestamp)";command.Connection=connection;command.CommandText=sql;command.Parameters.Add(newNpgsqlParameter("timestamp",timestamp));command.Parameters.Add(newNpgsqlParameter("id",1));command.ExecuteNonQuery();}using(varcommand=newNpgsqlCommand()){varsql="SELECT * FROM testtable WHERE id = @id";command.Connection=connection;command.CommandText=sql;command.Parameters.Add(newNpgsqlParameter("id",1));varreader=command.ExecuteReader();if(reader.Read()){varresultTimestamp=Convert.ToDateTime(reader["timestamp"]);if(!Compare(resultTimestamp.ToUniversalTime(),timestamp.ToUniversalTime()))thrownewException("Result was not as expected");}}...
static bool Compare(DateTimedt1,DateTimedt2){returndt1.Year==dt2.Year&&dt1.Month==dt2.Month&&dt1.Day==dt2.Day&&dt1.Hour==dt2.Hour&&dt1.Minute==dt2.Minute&&dt1.Second==dt2.Second;}
When setting postgresql.conf timezoen to: timezone = 'UTC'
...the above code works as expected and does not throw an exception
The issue
When saving a DateTime that has Kind = UTC, I expect it to be saved as UTC with the exact hour value being passed.
This is not what happens. If saving the value "yyyy-mm-dd 11:00:00" as UTC the value in postgres will be 11:00:00 as local time and converted to UTC it will be 10:00:00. The expected values is 12:00:00 local and 11:00:00 UTC
Postgres server timezone setting = UTC will produce the correct result. Other timezone settings will not (only tested with 'Europe/Brussels' value).
This issue only exists in NpgSql 4.x
NpgSql 3.x works as expected regardless of server timezone setting
Further technical details
Npgsql version: 4.0/4.3
PostgreSQL version: 9.6
Operating system: Windows 10
thrownewInvalidCastException("Out of the range of DateTime (year must be between 1 and 9999)");
returnnewDateTime(Ticks,Kind);
}
So now you're working with instances of the normal CLR DateTime, but I suspect the DateTimeKind of your resultTimestamp is still set to DateTimeKind.Unspecified. That's important because you then call .ToUniversalTime which has this remark in the docs (emphasis added):
Starting with the .NET Framework version 2.0, the value returned by the ToUniversalTime method is determined by the Kind property of the current DateTime object. The following table describes the possible results.
Kind
Results
Utc
No conversion is performed.
Local
The current DateTime object is converted to UTC.
Unspecified
The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.
So my suspicion is that you're getting a value back in the database timezone, but your code is treating it as though its in the local timezone when converting it into UTC.
Next steps
Have you tried adjusting the timezone in your connection string or by setting the PGTZ environment variable?
Thanks for the quick reply.
I dont think thats what's happening.
If I inspect the reader["timestamp"] value directly (before Convert.ToDateTime), it has Kind.Local. The value is equal to the expected UTC value.
Also the error happens on INSERT (I should have been more clear about that). The value in Postgres is wrong.
I have just run the test code. Time is now 17:16 local time (UTC+1). So I would expect to have 17:16 local and 16:16 UTC in the database.
I get this output in DBeaver:
Downgrading to NpgSql 3.2.7 and running again (5 minutes later), gives the expected result:
Btw I wasnt looking for a quick workaround. For now I'm settings postgres server to UTC as a workaround.
I was merely reporting the bug for the sake of the NpgSql project
Working with timezone-aware databases is a headache. Whenever possible, we recommend that users go turtles UTC all the way down. That is, only convert from/to local time when displaying to a human user.
Thanks for the quick reply.
I dont think thats what's happening.
If I inspect the reader["timestamp"] value directly (before Convert.ToDateTime), it has Kind.Local. The value is equal to the expected UTC value.
When saving a DateTime that has Kind = UTC, I expect it to be saved as UTC with the exact hour value being passed. This is not what happens.
This does appear to be happening. If I've understood you correctly, running SELECT * FROM testtable returns the UTC value inserted by Npgsql.
Is that not the case?
If saving the value "yyyy-mm-dd 11:00:00" as UTC the value in postgres will be 11:00:00 as local time and converted to UTC it will be 10:00:00. The expected values is 12:00:00 local and 11:00:00 UTC
PostgreSQL is showing you 11:00:00, but it isn't in local time, it's a UTC value. See below for some idea of why applying AT TIME ZONE 'UTC' to the already-is-UTC value returns 10:00:00.
Also the error happens on INSERT (I should have been more clear about that). The value in Postgres is wrong.
As above, I'm not sure that this is an error.
Your code inserts a timestamp and PostgreSQL stores it without any timezone information, as expected. The local column (which is a UTC value) in your first screenshot appears to show exactly that.
Converting the timestamp into a timestamptz is where things get wonky. See below for citations discussing why this happens:
By default DateTime is always sent as timestamp. No conversion is done. This is a breaking change.
timestamp is read as a DateTime with Kind=Unspecified. Same behavior as today.
It will no longer be possible to write DateTimeOffset to timestamp as it is in 3.x (trying to read currently throws an exception), I'm not sure why this was allowed in the first place. This is a breaking change.
Conversions between timestamp without time zone and timestamp with time zone normally assume that the timestamp without time zone value should be taken or given as timezone local time. A different time zone can be specified for the conversion using AT TIME ZONE.
Ok, first off the timestamp in my screenshot is local time not UTC.
Just to be clear I made the same test and screenshots in pgAdmin (to include the +/- timezone in display values).
Now passing this value: new DateTime(2018, 11, 1, 10, 0, 0, DateTimeKind.Utc);
pgAdmin shows:
(+01 confirming that the value is in local time)
What I get from the comments on #1803 is that it sounds like this is a deliberate breaking change from 3.x to 4!?
That, by default, DateTime.Kind is now ignored and DateTime is passed to Postgres as a timestamp (without time zone)!?
I can confirm that using this code, UTC is now actually saved as UTC:
var parameter = new NpgsqlParameter("timestamp", NpgsqlDbType.TimestampTz) { Value = timestamp };
command.Parameters.Add(parameter);
Not sure I understand the reason for this change, but I suspect other to run into the same issue.
Would it be possible to configure NpgSql to globally use TimestampTz for DateTime?
@nheilbuth there's one critical missing piece of information that's missing from your original post: the column types into which you're inserting.
As the release notes for 4.0 say, we had a behavior change where DateTime is always sent to PostgreSQL as timestamp without time zone (in 3.0 this depended on the Kind) - more detail is available in #1803 which you've already looked at. Now, if the database column you're inserting into is a timestamp with time zone, PostgreSQL will perform a conversion as per the docs. This could cause the somewhat unexpected behavior you're experiencing.
As @austindrenski mentioned above, at least in my view it's best to use columns of type timestamp without time zone (there are other opinions on this). This makes your database completely timezone un-aware - no timezone conversions will occur anywhere, neither in the driver nor in the database. IMHO this is a good thing and the way interaction with databases should work.
You might be right that using timestamp without time zone is best practice, but it still seems a bit odd to essentially drop support for timestamptz.
Migrating existing projects that use timestamptz could be quite a headache, and if you use Dapper on top of NpgSql, passing NpgsqlDbType.TimestampTz to the parameter is not an option.
You might be right that using timestamp without time zone is best practice, but it still seems a bit odd to essentially drop support for timestamptz.
Support for timestamptz definitely isn't dropped - you simply have to explicitly specify that you want to send timestamptz by setting NpgsqlDbType.Timestamptz on your NpgsqlParameter instance. This is again mentioned in the release notes, although I can see that the date/time mapping docs are out of date - I'll fix that soon.
In addition, DateTimeOffset is also sent as timestamptz by default, as before (although once again I can't say I recommend it).
Migrating existing projects that use timestamptz could be quite a headache, and if you use Dapper on top of NpgSql, passing NpgsqlDbType.TimestampTz to the parameter is not an option.
So if it is best practice to store the values as UTC in timestamp without timezone, What about the use case for SAAS where the application will connect to a separate database per tenant , but the codebase is the same. Where is the best place to do the conversion ? The tenant will have only 1 timezone for all users of the app... Is there a configuration call or an EF Core event hook I can place code in to lookup the current user's timezone and apply the necessary translation ?
Is there a configuration call or an EF Core event hook I can place code in to lookup the current user's timezone and apply the necessary translation ?
Hopefully I haven't misunderstood, but if you're asking, "where in the EF Core infrastructure should I handle time zone conversions?", then I believe our recommendation is still to avoid doing that work in the driver/ORM layer altogether.
Just one opinion, of course, but I expect it to almost always be far simpler to push those conversions to the app boundary, where (for example) NodaTime can work it's magic on incoming/outgoing data at the first/last possible moment.
Activity
austindrenski commentedon Oct 31, 2018
I'm not exactly sure what's happening, but I can take a look this evening if no one else has had time to respond before then.
In the meantime, here's a possible explanation and something to try on your end.
Possible explanation
The wire protocol sends
timestampvalues as signed 64-bit integers and Npgsql reads them intoNpgsqlDateTimelike so:npgsql/src/Npgsql/TypeHandlers/DateTimeHandlers/TimestampHandler.cs
Lines 102 to 114 in 9045b1f
That calls a constructor which defaults the
DateTimeKindtoDateTimeKind.Unspecified:npgsql/src/Npgsql/NpgsqlTypes/NpgsqlDateTime.cs
Lines 79 to 80 in 9045b1f
When you convert with
.ToDateTime, the ticks and kind are simply passed forward:npgsql/src/Npgsql/NpgsqlTypes/NpgsqlDateTime.cs
Lines 163 to 172 in 9045b1f
So now you're working with instances of the normal CLR
DateTime, but I suspect theDateTimeKindof yourresultTimestampis still set toDateTimeKind.Unspecified. That's important because you then call.ToUniversalTimewhich has this remark in the docs (emphasis added):So my suspicion is that you're getting a value back in the database timezone, but your code is treating it as though its in the local timezone when converting it into UTC.
Next steps
Have you tried adjusting the timezone in your connection string or by setting the
PGTZenvironment variable?Related
#1803
#1803 (comment)
nheilbuth commentedon Oct 31, 2018
Hi Austin
Thanks for the quick reply.
I dont think thats what's happening.
If I inspect the reader["timestamp"] value directly (before Convert.ToDateTime), it has Kind.Local. The value is equal to the expected UTC value.
Also the error happens on INSERT (I should have been more clear about that). The value in Postgres is wrong.
I have just run the test code. Time is now 17:16 local time (UTC+1). So I would expect to have 17:16 local and 16:16 UTC in the database.

I get this output in DBeaver:
Downgrading to NpgSql 3.2.7 and running again (5 minutes later), gives the expected result:

Btw I wasnt looking for a quick workaround. For now I'm settings postgres server to UTC as a workaround.
I was merely reporting the bug for the sake of the NpgSql project
austindrenski commentedon Oct 31, 2018
Working with timezone-aware databases is a headache. Whenever possible, we recommend that users go
turtlesUTC all the way down. That is, only convert from/to local time when displaying to a human user.This does appear to be happening. If I've understood you correctly, running
SELECT * FROM testtablereturns the UTC value inserted by Npgsql.Is that not the case?
PostgreSQL is showing you 11:00:00, but it isn't in local time, it's a UTC value. See below for some idea of why applying
AT TIME ZONE 'UTC'to the already-is-UTC value returns 10:00:00.As above, I'm not sure that this is an error.
Your code inserts a
timestampand PostgreSQL stores it without any timezone information, as expected. Thelocalcolumn (which is a UTC value) in your first screenshot appears to show exactly that.Converting the
timestampinto atimestamptzis where things get wonky. See below for citations discussing why this happens:Per #1803 (comment) and #1940:
Per the PosgreSQL docs:
nheilbuth commentedon Nov 1, 2018
Ok, first off the timestamp in my screenshot is local time not UTC.

Just to be clear I made the same test and screenshots in pgAdmin (to include the +/- timezone in display values).
Now passing this value:
new DateTime(2018, 11, 1, 10, 0, 0, DateTimeKind.Utc);pgAdmin shows:
(+01 confirming that the value is in local time)
What I get from the comments on #1803 is that it sounds like this is a deliberate breaking change from 3.x to 4!?
That, by default, DateTime.Kind is now ignored and DateTime is passed to Postgres as a timestamp (without time zone)!?
I can confirm that using this code, UTC is now actually saved as UTC:
Not sure I understand the reason for this change, but I suspect other to run into the same issue.
Would it be possible to configure NpgSql to globally use TimestampTz for DateTime?
roji commentedon Nov 1, 2018
@nheilbuth there's one critical missing piece of information that's missing from your original post: the column types into which you're inserting.
As the release notes for 4.0 say, we had a behavior change where
DateTimeis always sent to PostgreSQL astimestamp without time zone(in 3.0 this depended on the Kind) - more detail is available in #1803 which you've already looked at. Now, if the database column you're inserting into is atimestamp with time zone, PostgreSQL will perform a conversion as per the docs. This could cause the somewhat unexpected behavior you're experiencing.As @austindrenski mentioned above, at least in my view it's best to use columns of type
timestamp without time zone(there are other opinions on this). This makes your database completely timezone un-aware - no timezone conversions will occur anywhere, neither in the driver nor in the database. IMHO this is a good thing and the way interaction with databases should work.Let us know if this clarifies things.
nheilbuth commentedon Nov 1, 2018
Ah sorry. The column type is timestamptz.
Yes that clarifies things.
You might be right that using
timestamp without time zoneis best practice, but it still seems a bit odd to essentially drop support for timestamptz.Migrating existing projects that use timestamptz could be quite a headache, and if you use Dapper on top of NpgSql, passing
NpgsqlDbType.TimestampTzto the parameter is not an option.roji commentedon Nov 2, 2018
Support for
timestamptzdefinitely isn't dropped - you simply have to explicitly specify that you want to sendtimestamptzby settingNpgsqlDbType.Timestamptzon your NpgsqlParameter instance. This is again mentioned in the release notes, although I can see that the date/time mapping docs are out of date - I'll fix that soon.In addition,
DateTimeOffsetis also sent astimestamptzby default, as before (although once again I can't say I recommend it).That is not true - you can use Dapper's
ICustomQueryParameterto set NpgsqlDbType (see this stackoverflow for an example).Am going to close as no further action is needed on our side, but feel free to continue posting questions or suggestions to this issue.
nheilbuth commentedon Nov 2, 2018
Thanks that might come in handy
foote-Greg commentedon Jun 30, 2019
So if it is best practice to store the values as UTC in timestamp without timezone, What about the use case for SAAS where the application will connect to a separate database per tenant , but the codebase is the same. Where is the best place to do the conversion ? The tenant will have only 1 timezone for all users of the app... Is there a configuration call or an EF Core event hook I can place code in to lookup the current user's timezone and apply the necessary translation ?
Thanks,
Greg
austindrenski commentedon Jun 30, 2019
Hopefully I haven't misunderstood, but if you're asking, "where in the EF Core infrastructure should I handle time zone conversions?", then I believe our recommendation is still to avoid doing that work in the driver/ORM layer altogether.
Just one opinion, of course, but I expect it to almost always be far simpler to push those conversions to the app boundary, where (for example) NodaTime can work it's magic on incoming/outgoing data at the first/last possible moment.