From 55026b610687dae79d76af3dc64e5280cce09d74 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 24 Oct 2018 11:32:21 -0500 Subject: [PATCH] Add Convert A String To A Timestamp as a postgres til --- README.md | 3 +- postgres/convert-a-string-to-a-timestamp.md | 31 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 postgres/convert-a-string-to-a-timestamp.md diff --git a/README.md b/README.md index 4f2eeae..209c811 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_714 TILs and counting..._ +_715 TILs and counting..._ --- @@ -344,6 +344,7 @@ _714 TILs and counting..._ - [Compute The md5 Hash Of A String](postgres/compute-the-md5-hash-of-a-string.md) - [Configure The Timezone](postgres/configure-the-timezone.md) - [Constructing A Range Of Dates](postgres/constructing-a-range-of-dates.md) +- [Convert A String To A Timestamp](postgres/convert-a-string-to-a-timestamp.md) - [Count Records By Type](postgres/count-records-by-type.md) - [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md) - [Create hstore From Two Arrays](postgres/create-hstore-from-two-arrays.md) diff --git a/postgres/convert-a-string-to-a-timestamp.md b/postgres/convert-a-string-to-a-timestamp.md new file mode 100644 index 0000000..b73f435 --- /dev/null +++ b/postgres/convert-a-string-to-a-timestamp.md @@ -0,0 +1,31 @@ +# Convert A String To A Timestamp + +If you have a string that represents a point in time, there are a couple +ways that you can convert it to a PostgreSQL `timestamptz` value. + +If the string is in [ISO 8601 +format](https://en.wikipedia.org/wiki/ISO_8601), then it can be simply cast +to `timestamptz`. + +```sql +> select '2018-10-24'::timestamptz; + timestamptz +------------------------ + 2018-10-24 00:00:00-05 +``` + +A more general purpose approach is to use the +[`to_timestamp`](https://www.postgresql.org/docs/11/static/functions-formatting.html) +function. + +```sql +> select to_timestamp('2018-10-24', 'YYYY-MM-DD'); + to_timestamp +------------------------ + 2018-10-24 00:00:00-05 +``` + +The first argument is our string-to-be-converted in whatever format. The +second argument is another string describing in what format that string is. + +Note: Both of these approaches produce a `timestamptz` value.