Skip to content

Commit 55026b6

Browse files
committed
Add Convert A String To A Timestamp as a postgres til
1 parent 229387b commit 55026b6

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_714 TILs and counting..._
13+
_715 TILs and counting..._
1414

1515
---
1616

@@ -344,6 +344,7 @@ _714 TILs and counting..._
344344
- [Compute The md5 Hash Of A String](postgres/compute-the-md5-hash-of-a-string.md)
345345
- [Configure The Timezone](postgres/configure-the-timezone.md)
346346
- [Constructing A Range Of Dates](postgres/constructing-a-range-of-dates.md)
347+
- [Convert A String To A Timestamp](postgres/convert-a-string-to-a-timestamp.md)
347348
- [Count Records By Type](postgres/count-records-by-type.md)
348349
- [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md)
349350
- [Create hstore From Two Arrays](postgres/create-hstore-from-two-arrays.md)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Convert A String To A Timestamp
2+
3+
If you have a string that represents a point in time, there are a couple
4+
ways that you can convert it to a PostgreSQL `timestamptz` value.
5+
6+
If the string is in [ISO 8601
7+
format](https://en.wikipedia.org/wiki/ISO_8601), then it can be simply cast
8+
to `timestamptz`.
9+
10+
```sql
11+
> select '2018-10-24'::timestamptz;
12+
timestamptz
13+
------------------------
14+
2018-10-24 00:00:00-05
15+
```
16+
17+
A more general purpose approach is to use the
18+
[`to_timestamp`](https://www.postgresql.org/docs/11/static/functions-formatting.html)
19+
function.
20+
21+
```sql
22+
> select to_timestamp('2018-10-24', 'YYYY-MM-DD');
23+
to_timestamp
24+
------------------------
25+
2018-10-24 00:00:00-05
26+
```
27+
28+
The first argument is our string-to-be-converted in whatever format. The
29+
second argument is another string describing in what format that string is.
30+
31+
Note: Both of these approaches produce a `timestamptz` value.

0 commit comments

Comments
 (0)