SlideShare a Scribd company logo
1 of 9
Download to read offline
Taming The Snowflake DATE & TIMESTAMP Data
Manipulation & Arithmetic
(Faysal Shaarani)
Date and Time calculations are among the most widely used and most critical
computations in Analytics and Data Mining. The objective of this document is to
make your experience with Dates and Timestamps in Snowflake a smooth and
simple one.
Snowflake supports DATE and TIMESTAMP data types:
1. DATE: The DATE type stores dates (without time). Accepts dates in the
most common forms such as YYYY-MM-DD or DD-MON-YYYY etc. All
accepted timestamps are valid inputs for dates as well.
2. TIMESTAMP: Snowflake supports three flavors of the TIMESTAMP type
and a special TIMESTAMP alias. TIMESTAMP type in Snowflake is a
user-defined alias to one of the three types. In all operations where
TIMESTAMP can be used, the specified TIMESTAMP_ flavor will be used
automatically. The actual target type is controlled by
the TIMESTAMP_TYPE_MAPPING configuration option (by default it
is TIMESTAMP_LTZ) and TIMESTAMP type is never stored in the tables.
The timestamp_type_mapping can be set via the following command:
ALTER SESSION SET timestamp_type_
mapping = default;
	
The three TIMESTAMP types are:
a. TIMESTAMP_LTZ type internally stores UTC time with a specified
precision. All operations are performed in the current session's time
zone, controlled by the TIMEZONE parameter and can be changed
via the ALTER SESSION command:
ALTER SESSION SET
timezone = ‘America/Los_Angeles’;
b. TIMESTAMP_NTZ type internally stores "wallclock" time with a
specified precision. All operations are performed without taking any
time zone into account.
c. TIMESTAMP_TZ type internally stores UTC time together with an
associated time zone. When not provided, the session time zone is
used. All operations are performed in the time zone specific for
each record.
The DATE data type in Snowflake contains only date values (without the time
component). The TIMESTAMP data types in Snowflake contain date and time,
and optionally timezone.
Calendar Weeks and Weekdays
	
In Snowflake, the calendar week starts on Monday, following the ISO-8601
standard. This behavior influences functions like DATEDIFF and DATE_TRUNC.
Also, when extracting the “week” component in functions like DATE_PART and
EXTRACT, ISO week number is returned.
The “dayofweek_iso” component for EXTRACT and DATE_PART follows the
ISO behavior, returning 1 for Monday, 2 for Tuesday, …, 6 for Saturday and 7 for
Sunday. For compatibility with some other systems, the “dayofweek”
component returns 1 for Monday, 2 for Tuesday, …, 6 for Saturday, and 0 for
Sunday (following standard UNIX nomenclature).
Getting Current Date/Time
To get [Today’s Date] as DATE:
select current_date();
2014-08-05
To get [Today’s Date & Time] as TIMESTAMP_LTZ:
select current_timestamp();
Mon,	04	Aug	2014	17:13:02	-0700	
Extracting values
To get the [Day of the Week] as number (can be applied to any date or
timestamp):
select extract('dayofweek',current_date())
To get the [Name of the Day of the Week] as text (using CURRENT_DATE() as
an example):
This produces short English names, e.g. ‘Sun’, ‘Mon’ etc.
select to_varchar(current_date(), 'DY');
To use arbitrary, explicitly provided weekday names:
select DECODE(
extract ('dayofweek_iso',current_date()),
1, 'Monday',
2, 'Tuesday',
3, 'Wednesday',
4, 'Thursday',
5, 'Friday',
6, 'Saturday',
7, 'Sunday')
Computing Business Calendar:
To get the [First Day of the Current Month ] as DATE
SELECT DATE_TRUNC('month', current_date());
To get the [Last Day of the Current Month] as DATE:
select dateadd('day', -1,
dateadd('month', 1,
date_trunc('month', current_date())));
	
NOTE: In the above example, date_trunc finds the beginning of the current
month, the following addition of 1 month finds the beginning of the next month,
and final subtraction of 1 day finds the last day in the current month.
To get the [Last Day of the Prior Month] as DATE:
select dateadd(day, -1,
date_trunc('month',current_date()) );
To get the [Month of the Year By Name]:
Simple mode, using English abbreviated month names, e.g. “Jan” and “Dec”
select to_varchar(current_date(), 'Mon');
Using arbitrary, explicitly provided month names:
select DECODE extract('month',current_date())
1 , 'January',
2 , 'February',
3 , 'March',
4 , 'April',
5 , 'May',
6 , 'June',
7 , 'July',
8 , 'August',
9 , 'September',
10, 'October',
11, 'November',
12, 'December');
To get the [Date of the Monday of the Current Week]:
select dateadd(day, (extract('dayofweek_iso',
current_date()) * -1) +1 , current_date() );
To get the [Date of the Friday of the Current Week]:
Select dateadd('day', (5 - extract('dayofweek_iso',
current_date()) ), current_date() );
To get the [First Day of the Current Year] as DATE:
select date_trunc('year', current_date());
	
To get the [First Monday of the Current Month]:
select dateadd(
day,
MOD( 7 + 1 - date_part('dayofweek_iso',
date_trunc('month', current_date()) ), 7),
date_trunc('month', current_date()));
Note: “1” in the “7+1” above results in Monday. Use 2 for Tuesday…7 for
Sunday etc.
To get the [Last Day of the Current Year] as DATE:
select dateadd('day', -1,
dateadd('year', 1,
date_trunc('year', current_date())));
Note: To get the last day of the current month, use "month" instead of "year" on
the above SQL.
	
To get the [Last Day of the Prior Year] as DATE:
select dateadd('day', -1,
date_trunc('year',current_date()) );
To get the [First Day of the Quarter] as DATE:
select date_trunc('quarter',current_date());
To get the [Last Day of the Quarter] as DATE:
select dateadd('day', -1,
dateadd('month', 3,
date_trunc('quarter', current_date())));
	
To get [Midnight Time (Start of the day) of the Current Day]:
select date_trunc('day', current_timestamp() );
Other Date and Timestamp Operations
	
To get the [Date or Time Part of today’s Date and Time]:
select date_part(day, current_timestamp());
select date_part(year, current_timestamp());
select date_part(month, current_timestamp());
select date_part(hour, current_timestamp());
select date_part(minute, current_timestamp());
select date_part(second, current_timestamp());
OR
select extract('day', current_timestamp());
select extract('year', current_timestamp());
select extract('month', current_timestamp());
select extract('hour', current_timestamp());
select extract('minute', current_timestamp());
select extract('second', current_timestamp());	
OR
	
select day(current_timestamp() ) ,
hour( current_timestamp() ),
second(current_timestamp()),
minute(current_timestamp()),
month(current_timestamp());
NOTE: Please refer to the table below for additional Date/Time Parts
Masks.
	
[Date/Time Parts Masks]:
The following table lists different parts of dates and times that can be used by
various functions.
Date part or time part Abbreviations
Supported by
functions
Notes
year, years
y, yr, yrs, yy, yyy,
yyyy
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
quarter, quarters q, qtr, qtrs trunc, date_trunc
	
month, months mm, mon, mons
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
day, days d, dd
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
dayofweek, weekday dow, dw extract, date_part
Values returned are from 0
(Sunday) to 6 (Saturday). Note that
"week" component returns weeks
starting on Monday.
dayofweek_iso,
weekday_iso
dow_iso, dw_iso extract, date_part
Values returned are from 1
(Monday) to 7 (Sunday).
dayofyear, yearday doy, dy extract, date_part
	
week w, wk
extract, date_part,
date_trunc,
dateadd, datediff,
ISO week (starting on Monday). In
EXTRACT/DATE_PART, the
returned week number
corresponds to ISO 8601 weeks,
where a week belongs to the year
that contains a Thursday of that
week. It means, that the value
returned for days in early January
can be 52 or 53 (week belonging to
the previous year), and for days in
late December can be 1 (week
belonging to the next year).
weekofyear, wy, woy extract, date_part See discussion for "week".
hour, hours h, hr, hrs, hh
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
minute, minutes m, mi, min, mins
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
second, seconds s, sec, secs
extract, date_part,
trunc, date_trunc,
dateadd, datediff
	
nanosecond,
nanoseconds
ns, nsec, nsecs,
nsecond, nseconds,
nanosec, nanosecs
extract, date_part
	
timezone_hour tzh extract, date_part
	
timezone_minute tzm extract, date_part
	
To add [Different Time Increments to a Date Value]:
select dateadd(year, 2, current_date());
select dateadd(day,2,current_date());
select dateadd(hour,2,current_timestamp());
select dateadd(minute,2,current_timestamp());
select dateadd(second,2,current_timestamp());
To [Convert a Valid Character String to a Timestamp]:
select to_timestamp ('12-jan-2013 00:00:00','dd-mon-yyyy
hh:mi:ss');
	
To [Perform Date Arithmetic on a Valid Date String]:
select dateadd('day',5, to_timestamp ('12-jan-2013
00:00:00','dd-mon-yyyy hh:mi:ss') );
	
select datediff('day', to_timestamp ('12-jan-2013
00:00:00','dd-mon-yyyy hh:mi:ss') , current_date() );
select datediff('day', to_date ('12-jan-2013 00:00:00','dd-
mon-yyyy hh:mi:ss') , current_date() );
To [Insert a Valid Date String Into a Table with Date Column]:
Create table test (date1 date);
insert into test values (to_date ('12-jan-2013
00:00:00','dd-mon-yyyy hh:mi:ss'));
2013-01-12	
	
insert into test values (to_date ('11:30:40','hh:mi:ss'));
1970-01-01	
	
select to_varchar(date1, 'dd-mon-yyyy hh:mi:ss') from test;
12-Jan-2013	00:00:00	
01-Jan-1970	00:00:00	
	
To compute [The Difference Between Two Dates]:
select datediff(year, current_date(),
dateadd(year, 3, current_date() ) );
select datediff(month, current_date(),
dateadd(month, 3, current_date()) );
select datediff(day, current_date(),
dateadd(day, 3, current_date()) );
select datediff(hour, current_timestamp(),
dateadd(hour, 3, current_timestamp()) );
select datediff(minute, current_timestamp(),
dateadd(minute, 3, current_timestamp()) );
select datediff(second, current_timestamp(),
dateadd(second, 3, current_timestamp()) );
To create a [Yearly Calendar View in Snowflake]:
create or replace view calendar_2014 as
select n, theDate,
decode (extract('dayofweek',theDate),
1 , 'Monday',
2 , 'Tuesday',
3 , 'Wednesday',
4 , 'Thursday',
5 , 'Friday',
6 , 'Saturday',
0 , 'Sunday'
) theDayOfTheWeek,
decode (extract(month from theDate),
1 , 'January',
2 , 'February',
3 , 'March',
4 , 'April',
5 , 'May',
6 , 'June',
7 , 'July',
8 , 'August',
9 , 'september',
10, 'October',
11, 'November',
12, 'December'
) theMonth,
extract(year from theDate) theYear
from
( select
row_number() over (order by seq4()) as n,
dateadd(day, row_number() over (order by
seq4())-1, to_date('2014-01-01'))
as theDate
from table(generator(rowCount => 365))) order
by n asc;

More Related Content

What's hot

Data Mesh for Dinner
Data Mesh for DinnerData Mesh for Dinner
Data Mesh for DinnerKent Graziano
 
Snowflake for Data Engineering
Snowflake for Data EngineeringSnowflake for Data Engineering
Snowflake for Data EngineeringHarald Erb
 
SAP Integration: Best Practices | MuleSoft
SAP Integration: Best Practices | MuleSoftSAP Integration: Best Practices | MuleSoft
SAP Integration: Best Practices | MuleSoftMuleSoft
 
Dell Boomi Integration with Salesforce
Dell Boomi Integration with SalesforceDell Boomi Integration with Salesforce
Dell Boomi Integration with SalesforceNagarjuna Kaipu
 
Introduction to Data Vault Modeling
Introduction to Data Vault ModelingIntroduction to Data Vault Modeling
Introduction to Data Vault ModelingKent Graziano
 
An overview of snowflake
An overview of snowflakeAn overview of snowflake
An overview of snowflakeSivakumar Ramar
 
Introduction to lightning Web Component
Introduction to lightning Web ComponentIntroduction to lightning Web Component
Introduction to lightning Web ComponentMohith Shrivastava
 
Salesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsSalesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsCloud Analogy
 
Snowflake Best Practices for Elastic Data Warehousing
Snowflake Best Practices for Elastic Data WarehousingSnowflake Best Practices for Elastic Data Warehousing
Snowflake Best Practices for Elastic Data WarehousingAmazon Web Services
 
Tableau slideshare
Tableau slideshareTableau slideshare
Tableau slideshareSakshi Jain
 
Complete Guide To Salesforce Einstein Analytics
Complete Guide To Salesforce Einstein AnalyticsComplete Guide To Salesforce Einstein Analytics
Complete Guide To Salesforce Einstein AnalyticsCloud Analogy
 
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...CzechDreamin
 
Introduction to snowflake
Introduction to snowflakeIntroduction to snowflake
Introduction to snowflakeSunil Gurav
 
The Power Of Snowflake for SAP BusinessObjects
The Power Of Snowflake for SAP BusinessObjectsThe Power Of Snowflake for SAP BusinessObjects
The Power Of Snowflake for SAP BusinessObjectsWiiisdom
 

What's hot (20)

Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Data Mesh for Dinner
Data Mesh for DinnerData Mesh for Dinner
Data Mesh for Dinner
 
Snowflake for Data Engineering
Snowflake for Data EngineeringSnowflake for Data Engineering
Snowflake for Data Engineering
 
SAP Integration: Best Practices | MuleSoft
SAP Integration: Best Practices | MuleSoftSAP Integration: Best Practices | MuleSoft
SAP Integration: Best Practices | MuleSoft
 
Informatica session
Informatica sessionInformatica session
Informatica session
 
Salesforce PPT.pptx
Salesforce PPT.pptxSalesforce PPT.pptx
Salesforce PPT.pptx
 
Dell Boomi Integration with Salesforce
Dell Boomi Integration with SalesforceDell Boomi Integration with Salesforce
Dell Boomi Integration with Salesforce
 
snowpro (1).pdf
snowpro (1).pdfsnowpro (1).pdf
snowpro (1).pdf
 
Introduction to Data Vault Modeling
Introduction to Data Vault ModelingIntroduction to Data Vault Modeling
Introduction to Data Vault Modeling
 
SAP BW - Info cube
SAP BW - Info cubeSAP BW - Info cube
SAP BW - Info cube
 
An overview of snowflake
An overview of snowflakeAn overview of snowflake
An overview of snowflake
 
Introduction to lightning Web Component
Introduction to lightning Web ComponentIntroduction to lightning Web Component
Introduction to lightning Web Component
 
Salesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsSalesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More Deals
 
Tableau Desktop Material
Tableau Desktop MaterialTableau Desktop Material
Tableau Desktop Material
 
Snowflake Best Practices for Elastic Data Warehousing
Snowflake Best Practices for Elastic Data WarehousingSnowflake Best Practices for Elastic Data Warehousing
Snowflake Best Practices for Elastic Data Warehousing
 
Tableau slideshare
Tableau slideshareTableau slideshare
Tableau slideshare
 
Complete Guide To Salesforce Einstein Analytics
Complete Guide To Salesforce Einstein AnalyticsComplete Guide To Salesforce Einstein Analytics
Complete Guide To Salesforce Einstein Analytics
 
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...
Salesforce Forecasting: Evolution, Implementation and Best Practices, Christi...
 
Introduction to snowflake
Introduction to snowflakeIntroduction to snowflake
Introduction to snowflake
 
The Power Of Snowflake for SAP BusinessObjects
The Power Of Snowflake for SAP BusinessObjectsThe Power Of Snowflake for SAP BusinessObjects
The Power Of Snowflake for SAP BusinessObjects
 

Viewers also liked

100 consejos-para-mejorar-la-publicidad-inmobiliaria
100 consejos-para-mejorar-la-publicidad-inmobiliaria100 consejos-para-mejorar-la-publicidad-inmobiliaria
100 consejos-para-mejorar-la-publicidad-inmobiliariaCARLOS DAVID BELTRAN OGANDO
 
Career exploration
Career explorationCareer exploration
Career explorationrosiebud88
 
What to do in a dental emergency
What to do in a dental emergencyWhat to do in a dental emergency
What to do in a dental emergencyTiffany Kate Roth
 
HU_UK_Photo collage 1_products_GENERAL 2016
HU_UK_Photo collage 1_products_GENERAL 2016HU_UK_Photo collage 1_products_GENERAL 2016
HU_UK_Photo collage 1_products_GENERAL 2016davidmclaren
 
الامن الصناعى
الامن الصناعىالامن الصناعى
الامن الصناعىmohamed nemila
 
Кожаная флористика
Кожаная флористикаКожаная флористика
Кожаная флористикаbobic_731
 
Гобелен искуство, приносящее радость
Гобелен   искуство, приносящее радостьГобелен   искуство, приносящее радость
Гобелен искуство, приносящее радостьbobic_731
 
Мезенская роспись
Мезенская росписьМезенская роспись
Мезенская росписьbobic_731
 
Уроки мастерства
Уроки мастерстваУроки мастерства
Уроки мастерстваbobic_731
 
Manual de inspeccion de equipos de aplicacion de fitosanitarios
Manual de inspeccion de equipos de aplicacion de fitosanitariosManual de inspeccion de equipos de aplicacion de fitosanitarios
Manual de inspeccion de equipos de aplicacion de fitosanitariosGuadalinfo Escañuela
 

Viewers also liked (15)

100 consejos-para-mejorar-la-publicidad-inmobiliaria
100 consejos-para-mejorar-la-publicidad-inmobiliaria100 consejos-para-mejorar-la-publicidad-inmobiliaria
100 consejos-para-mejorar-la-publicidad-inmobiliaria
 
La integración de las tic en la educación
La integración de las tic en la educaciónLa integración de las tic en la educación
La integración de las tic en la educación
 
Multimedia y multimedios
Multimedia y multimediosMultimedia y multimedios
Multimedia y multimedios
 
Career exploration
Career explorationCareer exploration
Career exploration
 
What to do in a dental emergency
What to do in a dental emergencyWhat to do in a dental emergency
What to do in a dental emergency
 
HU_UK_Photo collage 1_products_GENERAL 2016
HU_UK_Photo collage 1_products_GENERAL 2016HU_UK_Photo collage 1_products_GENERAL 2016
HU_UK_Photo collage 1_products_GENERAL 2016
 
La publicidad
La publicidadLa publicidad
La publicidad
 
GNDKP
GNDKPGNDKP
GNDKP
 
الامن الصناعى
الامن الصناعىالامن الصناعى
الامن الصناعى
 
Кожаная флористика
Кожаная флористикаКожаная флористика
Кожаная флористика
 
Гобелен искуство, приносящее радость
Гобелен   искуство, приносящее радостьГобелен   искуство, приносящее радость
Гобелен искуство, приносящее радость
 
Мезенская роспись
Мезенская росписьМезенская роспись
Мезенская роспись
 
Уроки мастерства
Уроки мастерстваУроки мастерства
Уроки мастерства
 
Manual de inspeccion de equipos de aplicacion de fitosanitarios
Manual de inspeccion de equipos de aplicacion de fitosanitariosManual de inspeccion de equipos de aplicacion de fitosanitarios
Manual de inspeccion de equipos de aplicacion de fitosanitarios
 
Ruhaniyat Snaps
Ruhaniyat SnapsRuhaniyat Snaps
Ruhaniyat Snaps
 

Similar to Date and Timestamp Types In Snowflake (By Faysal Shaarani)

How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3allanh0526
 
Hi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdfHi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdfAnkitchhabra28
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeHellen Gakuruh
 
Date time function in Database
Date time function in DatabaseDate time function in Database
Date time function in DatabaseSarfaraz Ghanta
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8Serhii Kartashov
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
sql_server_2016_history_tables
sql_server_2016_history_tablessql_server_2016_history_tables
sql_server_2016_history_tablesarthurjosemberg
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4Kenji HASUNUMA
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Fulvio Corno
 
Assignment Details There is a .h file on Moodle that provides a defi.pdf
Assignment Details There is a .h file on Moodle that provides a defi.pdfAssignment Details There is a .h file on Moodle that provides a defi.pdf
Assignment Details There is a .h file on Moodle that provides a defi.pdfjyothimuppasani1
 

Similar to Date and Timestamp Types In Snowflake (By Faysal Shaarani) (20)

How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
 
Les05
Les05Les05
Les05
 
Hi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdfHi,I have implemented increment() method. Please find the below up.pdf
Hi,I have implemented increment() method. Please find the below up.pdf
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTime
 
Date time function in Database
Date time function in DatabaseDate time function in Database
Date time function in Database
 
datetimefuction-170413055211.pptx
datetimefuction-170413055211.pptxdatetimefuction-170413055211.pptx
datetimefuction-170413055211.pptx
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Oracle Date Functions
Oracle Date FunctionsOracle Date Functions
Oracle Date Functions
 
sql_server_2016_history_tables
sql_server_2016_history_tablessql_server_2016_history_tables
sql_server_2016_history_tables
 
Introduction to Date and Time API 4
Introduction to Date and Time API 4Introduction to Date and Time API 4
Introduction to Date and Time API 4
 
Java 8 Date and Time API
Java 8 Date and Time APIJava 8 Date and Time API
Java 8 Date and Time API
 
20 date-times
20 date-times20 date-times
20 date-times
 
10. timestamp
10. timestamp10. timestamp
10. timestamp
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
doc
docdoc
doc
 
jkfdlsajfklafj
jkfdlsajfklafjjkfdlsajfklafj
jkfdlsajfklafj
 
Script Files
Script FilesScript Files
Script Files
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
Assignment Details There is a .h file on Moodle that provides a defi.pdf
Assignment Details There is a .h file on Moodle that provides a defi.pdfAssignment Details There is a .h file on Moodle that provides a defi.pdf
Assignment Details There is a .h file on Moodle that provides a defi.pdf
 

Date and Timestamp Types In Snowflake (By Faysal Shaarani)

  • 1. Taming The Snowflake DATE & TIMESTAMP Data Manipulation & Arithmetic (Faysal Shaarani) Date and Time calculations are among the most widely used and most critical computations in Analytics and Data Mining. The objective of this document is to make your experience with Dates and Timestamps in Snowflake a smooth and simple one. Snowflake supports DATE and TIMESTAMP data types: 1. DATE: The DATE type stores dates (without time). Accepts dates in the most common forms such as YYYY-MM-DD or DD-MON-YYYY etc. All accepted timestamps are valid inputs for dates as well. 2. TIMESTAMP: Snowflake supports three flavors of the TIMESTAMP type and a special TIMESTAMP alias. TIMESTAMP type in Snowflake is a user-defined alias to one of the three types. In all operations where TIMESTAMP can be used, the specified TIMESTAMP_ flavor will be used automatically. The actual target type is controlled by the TIMESTAMP_TYPE_MAPPING configuration option (by default it is TIMESTAMP_LTZ) and TIMESTAMP type is never stored in the tables. The timestamp_type_mapping can be set via the following command: ALTER SESSION SET timestamp_type_ mapping = default; The three TIMESTAMP types are: a. TIMESTAMP_LTZ type internally stores UTC time with a specified precision. All operations are performed in the current session's time zone, controlled by the TIMEZONE parameter and can be changed via the ALTER SESSION command: ALTER SESSION SET timezone = ‘America/Los_Angeles’;
  • 2. b. TIMESTAMP_NTZ type internally stores "wallclock" time with a specified precision. All operations are performed without taking any time zone into account. c. TIMESTAMP_TZ type internally stores UTC time together with an associated time zone. When not provided, the session time zone is used. All operations are performed in the time zone specific for each record. The DATE data type in Snowflake contains only date values (without the time component). The TIMESTAMP data types in Snowflake contain date and time, and optionally timezone. Calendar Weeks and Weekdays In Snowflake, the calendar week starts on Monday, following the ISO-8601 standard. This behavior influences functions like DATEDIFF and DATE_TRUNC. Also, when extracting the “week” component in functions like DATE_PART and EXTRACT, ISO week number is returned. The “dayofweek_iso” component for EXTRACT and DATE_PART follows the ISO behavior, returning 1 for Monday, 2 for Tuesday, …, 6 for Saturday and 7 for Sunday. For compatibility with some other systems, the “dayofweek” component returns 1 for Monday, 2 for Tuesday, …, 6 for Saturday, and 0 for Sunday (following standard UNIX nomenclature). Getting Current Date/Time To get [Today’s Date] as DATE: select current_date(); 2014-08-05 To get [Today’s Date & Time] as TIMESTAMP_LTZ: select current_timestamp(); Mon, 04 Aug 2014 17:13:02 -0700 Extracting values To get the [Day of the Week] as number (can be applied to any date or timestamp): select extract('dayofweek',current_date())
  • 3. To get the [Name of the Day of the Week] as text (using CURRENT_DATE() as an example): This produces short English names, e.g. ‘Sun’, ‘Mon’ etc. select to_varchar(current_date(), 'DY'); To use arbitrary, explicitly provided weekday names: select DECODE( extract ('dayofweek_iso',current_date()), 1, 'Monday', 2, 'Tuesday', 3, 'Wednesday', 4, 'Thursday', 5, 'Friday', 6, 'Saturday', 7, 'Sunday') Computing Business Calendar: To get the [First Day of the Current Month ] as DATE SELECT DATE_TRUNC('month', current_date()); To get the [Last Day of the Current Month] as DATE: select dateadd('day', -1, dateadd('month', 1, date_trunc('month', current_date()))); NOTE: In the above example, date_trunc finds the beginning of the current month, the following addition of 1 month finds the beginning of the next month, and final subtraction of 1 day finds the last day in the current month. To get the [Last Day of the Prior Month] as DATE: select dateadd(day, -1, date_trunc('month',current_date()) ); To get the [Month of the Year By Name]: Simple mode, using English abbreviated month names, e.g. “Jan” and “Dec” select to_varchar(current_date(), 'Mon'); Using arbitrary, explicitly provided month names:
  • 4. select DECODE extract('month',current_date()) 1 , 'January', 2 , 'February', 3 , 'March', 4 , 'April', 5 , 'May', 6 , 'June', 7 , 'July', 8 , 'August', 9 , 'September', 10, 'October', 11, 'November', 12, 'December'); To get the [Date of the Monday of the Current Week]: select dateadd(day, (extract('dayofweek_iso', current_date()) * -1) +1 , current_date() ); To get the [Date of the Friday of the Current Week]: Select dateadd('day', (5 - extract('dayofweek_iso', current_date()) ), current_date() ); To get the [First Day of the Current Year] as DATE: select date_trunc('year', current_date()); To get the [First Monday of the Current Month]: select dateadd( day, MOD( 7 + 1 - date_part('dayofweek_iso', date_trunc('month', current_date()) ), 7), date_trunc('month', current_date())); Note: “1” in the “7+1” above results in Monday. Use 2 for Tuesday…7 for Sunday etc. To get the [Last Day of the Current Year] as DATE: select dateadd('day', -1, dateadd('year', 1, date_trunc('year', current_date()))); Note: To get the last day of the current month, use "month" instead of "year" on the above SQL. To get the [Last Day of the Prior Year] as DATE: select dateadd('day', -1, date_trunc('year',current_date()) );
  • 5. To get the [First Day of the Quarter] as DATE: select date_trunc('quarter',current_date()); To get the [Last Day of the Quarter] as DATE: select dateadd('day', -1, dateadd('month', 3, date_trunc('quarter', current_date()))); To get [Midnight Time (Start of the day) of the Current Day]: select date_trunc('day', current_timestamp() ); Other Date and Timestamp Operations To get the [Date or Time Part of today’s Date and Time]: select date_part(day, current_timestamp()); select date_part(year, current_timestamp()); select date_part(month, current_timestamp()); select date_part(hour, current_timestamp()); select date_part(minute, current_timestamp()); select date_part(second, current_timestamp()); OR select extract('day', current_timestamp()); select extract('year', current_timestamp()); select extract('month', current_timestamp()); select extract('hour', current_timestamp()); select extract('minute', current_timestamp()); select extract('second', current_timestamp()); OR select day(current_timestamp() ) , hour( current_timestamp() ), second(current_timestamp()), minute(current_timestamp()), month(current_timestamp()); NOTE: Please refer to the table below for additional Date/Time Parts Masks. [Date/Time Parts Masks]: The following table lists different parts of dates and times that can be used by various functions.
  • 6. Date part or time part Abbreviations Supported by functions Notes year, years y, yr, yrs, yy, yyy, yyyy extract, date_part, trunc, date_trunc, dateadd, datediff quarter, quarters q, qtr, qtrs trunc, date_trunc month, months mm, mon, mons extract, date_part, trunc, date_trunc, dateadd, datediff day, days d, dd extract, date_part, trunc, date_trunc, dateadd, datediff dayofweek, weekday dow, dw extract, date_part Values returned are from 0 (Sunday) to 6 (Saturday). Note that "week" component returns weeks starting on Monday. dayofweek_iso, weekday_iso dow_iso, dw_iso extract, date_part Values returned are from 1 (Monday) to 7 (Sunday). dayofyear, yearday doy, dy extract, date_part week w, wk extract, date_part, date_trunc, dateadd, datediff, ISO week (starting on Monday). In EXTRACT/DATE_PART, the returned week number corresponds to ISO 8601 weeks, where a week belongs to the year that contains a Thursday of that week. It means, that the value
  • 7. returned for days in early January can be 52 or 53 (week belonging to the previous year), and for days in late December can be 1 (week belonging to the next year). weekofyear, wy, woy extract, date_part See discussion for "week". hour, hours h, hr, hrs, hh extract, date_part, trunc, date_trunc, dateadd, datediff minute, minutes m, mi, min, mins extract, date_part, trunc, date_trunc, dateadd, datediff second, seconds s, sec, secs extract, date_part, trunc, date_trunc, dateadd, datediff nanosecond, nanoseconds ns, nsec, nsecs, nsecond, nseconds, nanosec, nanosecs extract, date_part timezone_hour tzh extract, date_part timezone_minute tzm extract, date_part To add [Different Time Increments to a Date Value]: select dateadd(year, 2, current_date()); select dateadd(day,2,current_date()); select dateadd(hour,2,current_timestamp()); select dateadd(minute,2,current_timestamp()); select dateadd(second,2,current_timestamp());
  • 8. To [Convert a Valid Character String to a Timestamp]: select to_timestamp ('12-jan-2013 00:00:00','dd-mon-yyyy hh:mi:ss'); To [Perform Date Arithmetic on a Valid Date String]: select dateadd('day',5, to_timestamp ('12-jan-2013 00:00:00','dd-mon-yyyy hh:mi:ss') ); select datediff('day', to_timestamp ('12-jan-2013 00:00:00','dd-mon-yyyy hh:mi:ss') , current_date() ); select datediff('day', to_date ('12-jan-2013 00:00:00','dd- mon-yyyy hh:mi:ss') , current_date() ); To [Insert a Valid Date String Into a Table with Date Column]: Create table test (date1 date); insert into test values (to_date ('12-jan-2013 00:00:00','dd-mon-yyyy hh:mi:ss')); 2013-01-12 insert into test values (to_date ('11:30:40','hh:mi:ss')); 1970-01-01 select to_varchar(date1, 'dd-mon-yyyy hh:mi:ss') from test; 12-Jan-2013 00:00:00 01-Jan-1970 00:00:00 To compute [The Difference Between Two Dates]: select datediff(year, current_date(), dateadd(year, 3, current_date() ) ); select datediff(month, current_date(), dateadd(month, 3, current_date()) ); select datediff(day, current_date(), dateadd(day, 3, current_date()) ); select datediff(hour, current_timestamp(), dateadd(hour, 3, current_timestamp()) ); select datediff(minute, current_timestamp(), dateadd(minute, 3, current_timestamp()) ); select datediff(second, current_timestamp(), dateadd(second, 3, current_timestamp()) );
  • 9. To create a [Yearly Calendar View in Snowflake]: create or replace view calendar_2014 as select n, theDate, decode (extract('dayofweek',theDate), 1 , 'Monday', 2 , 'Tuesday', 3 , 'Wednesday', 4 , 'Thursday', 5 , 'Friday', 6 , 'Saturday', 0 , 'Sunday' ) theDayOfTheWeek, decode (extract(month from theDate), 1 , 'January', 2 , 'February', 3 , 'March', 4 , 'April', 5 , 'May', 6 , 'June', 7 , 'July', 8 , 'August', 9 , 'september', 10, 'October', 11, 'November', 12, 'December' ) theMonth, extract(year from theDate) theYear from ( select row_number() over (order by seq4()) as n, dateadd(day, row_number() over (order by seq4())-1, to_date('2014-01-01')) as theDate from table(generator(rowCount => 365))) order by n asc;