Npgsql Insert Time Without Timezone

I’m just getting started with Npgsql for .NET Core Entity Framework and I ran into some trouble trying to do an insert into a Postgres table with a time data type. I initially tried to use a DateTime object, as worked with the date data type, but that didn’t work. The documentation said to use a TimeSpan, but I didn’t know what to span. Here’s what I did to get it to work.


I was confused because the .NET docs for the TimeSpan showed spans being created by subtracting dates. I thought I was expected to input a span between two time instants. I tried converting a Unix time stamp (the span of seconds since January 1, 1970) to a TimeSpan but that didn’t work. Finally, I just put the current time into the TimeSpan constructor.

using (var context = new PostsContext())
    Post post = new Post();
    post.Date = DateTime.UtcNow;
    post.Time = new TimeSpan(DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second);
    post.Author = "John Q.";
    post.Text = "Hello World!";


Leave a Reply

Your email address will not be published.