Those of us who use Rails will not be surprised when they see 5. weeks. from_nowor3.days.ago + 2. hours. Similarly, PostgreSQL can also achieve the same functionality by simply calling the built-in functions of PostgreSQL.
PostgreSQL deletes duplicate data rows in a table
Establishment of PostgreSQL database connection pool PgBouncer
Compiling PostgreSQL on Windows
Notes on PostgreSQL backup
PostgreSQL details: click here
PostgreSQL: click here
Current Time/date/Timestamp
There are many ways to get the current time. Before that, we need to know the differences between the following two types:
- Always Returns the current value (clock_timestamp ())
- Always Returns the current value, but in the transaction it returns the start time of the transaction (now ())
Let's take a look at the example below
S = # BEGIN;
Postgres = # SELECT now ();
Now
-------------------------------
12:17:43. 182331 + 02
Postgres = # SELECT now ();
Now
-------------------------------
12:17:43. 182331 + 02
Postgres = # SELECT clock_timestamp ();
Clock_timestamp
-------------------------------
12:17:50. 698413 + 02
Postgres = # SELECT clock_timestamp ();
Clock_timestamp
-------------------------------
12:17:51. 123905 + 02
You will find that the clock_timestamp () returned value changes every time when the statement is executed, but now () always returns the same value. When you need to consider the time zone, you should pay special attention to the differences between the two functions.
Time Range: for example, 3 days ago
Using the interval operator, you can easily build a time interval, for example
- Interval '1 Day'
- Interval '5 days'
- Interval '5 days '+ interval '3 urs'
- Interval '5 days 3 urs'
As you can see, we can use the interval operator for simple mathematical operations. This is especially suitable for building time ranges such as three days ago, for example:
Postgres = # SELECT now ()-interval '3 days ';
? Column?
-------------------------------
12:23:40. 069717 + 02
Obtain the day of the week
Sometimes, for a given time, you only want to know the day of the week, the day of the century, or the day of the year. The extract () function in PostgreSQL provides this function.
The following example is a test conducted on Monday, August 26.
Postgres = # SELECT extract (day from now ());
Date_part
-----------
26
Postgres = # SELECT extract (dow from now ());
Date_part
-----------
1
Extract () has other more powerful functions. For more information, see the official documentation. Here we only list a small part:
- Day
- Century
- Dow (day of week)
- Doy (day of year)
- Minute
- Month
- Year