sqlpostgresqldatepart

Extract weekday, millisecond, microsecond, nanosecond from a date in Postgres


How to extract the millisecond, weekday, microsecond, nanosecond from a date in Postgres. I have tried the extract methods too, but I could not find an exact equivalent.


Solution

  • I'm not sure what equivalent are you looking for, but:

    If you are looking for logically separate values, you'll need to do some math, e.g.:

    select extract(dow from ts) dow,       -- day-of-week (where weeks start on sunday, which is 0)
           extract(isodow from ts) isodow, -- ISO day-of-week (where weeks start on monday, which is 1)
           floor(extract(seconds from ts))::int only_seconds,
           floor(extract(milliseconds from ts))::int - 1000 * floor(extract(seconds from ts))::int only_milliseconds,
           floor(extract(microseconds from ts))::int - 1000 * floor(extract(milliseconds from ts))::int only_microseconds,
           extract(microseconds from ts) all_microseconds
    

    Or, if you are looking to how far a timestamp is within its actual week, you can use timestamp (and interval) arithmetics too:

    select ts - date_trunc('week', ts) time_elapsed_since_monday
    

    (Although it is rather hard to calculate this for weeks which start on sunday: date_trunc works with only ISO weeks).

    http://rextester.com/SOOO48159