Dates: Advanced

Bloomberg Terminal serves over 325,000 financial professionals who depend on real-time and historical date calculations to make billion-dollar investment decisions, including rolling 52-week highs, year-over-year revenue growth comparisons, and cohort retention curves that determine whether a fund manager buys or sells a position. These calculations require timezone-aware timestamps, date truncation to align data to fiscal periods, and the ability to parse dates from dozens of different data sources and formats. A query that truncates to the wrong period boundary or converts a timezone incorrectly can make a stock look like it hit a new high when it did not. This lesson covers the advanced date handling techniques that production financial and analytical systems rely on every day.

Timezone Control

Daily Life
Interviews

Convert times across global time zones

Timestamps without timezone context are ambiguous. "2024-01-15 10:00:00" could be UTC, Pacific, or any timezone. SQL provides functions to attach timezone information and convert between zones.

Timezone Types

SQL has two timestamp types: TIMESTAMP (no timezone) and TIMESTAMP WITH TIME ZONE. The latter stores UTC internally but displays in your session timezone.

TIMESTAMP
  • No timezone info
  • Ambiguous across regions
  • Assumes local time
  • Use for: birth dates, deadlines
TIMESTAMP WITH TIME ZONE
  • Stores UTC + offset
  • Unambiguous globally
  • Converts for display
  • Use for: events, API timestamps

Converting Timezones

Use AT TIME ZONE to convert timestamps between timezones.

1SELECT
2 event_time,
3 event_time AT TIME ZONE 'UTC' AS utc_time,
4 event_time AT TIME ZONE 'America/New_York' AS ny_time,
5 event_time AT TIME ZONE 'Asia/Tokyo' AS tokyo_time
6FROM event_data
Result
event_timeutc_timeny_timetokyo_time
2024-01-15 10:00:002024-01-15 10:00:002024-01-15 05:00:002024-01-15 19:00:00
The same instant appears differently in each timezone. Tokyo is 9 hours ahead of UTC, so 10:00 UTC becomes 19:00 Tokyo.

Time Across Multiple Zones

For real-time dashboards, show current time in each region where users operate.
1SELECT
2 CURRENT_TIMESTAMP AS server_time,
3 CURRENT_TIMESTAMP AT TIME ZONE 'America/Los_Angeles' AS pacific,
4 CURRENT_TIMESTAMP AT TIME ZONE 'America/New_York' AS eastern,
5 CURRENT_TIMESTAMP AT TIME ZONE 'Europe/London' AS london
Result
server_timepacificeasternlondon
2024-01-15 10:00:00 UTC2024-01-15 02:00:002024-01-15 05:00:002024-01-15 10:00:00

Daylight Saving Time

DST adds complexity. In March and November, some hours repeat or don't exist. SQL handles this automatically, but be aware of edge cases.
TIP
Always store timestamps in UTC to avoid DST ambiguity. Convert to local timezone only for display.

> Convert a UTC timestamp to Pacific timezone.

SELECT
  event_timestamp ___ ___ AS pacific_time
FROM event_data
'America/Los_Angeles'
TIME ZONE
AT TIME ZONE
'UTC'

AT TIME ZONE preserves the absolute moment in time while changing only the display offset. The underlying UTC value never changes, making conversions fully reversible and safe for calculations.

IANA timezone names like America/Los_Angeles handle Daylight Saving Time automatically. Using fixed offsets such as UTC-8 breaks twice a year when clocks change.
Always store timestamps in UTC in your database and convert to the user's local timezone at display time. This keeps the data unambiguous and makes timezone changes trivial to apply.

DATE_TRUNC()

Daily Life
Interviews

Snap timestamps to clean boundaries

DATE_TRUNC rounds timestamps down to the start of a unit (day, week, month, year). This is essential for grouping by time periods.

Truncating to Common Units

Truncate to day, week, month, or year to group timestamps into buckets for aggregation.
1SELECT
2 event_time,
3 DATE_TRUNC('day', event_time) AS day_start,
4 DATE_TRUNC('week', event_time) AS week_start,
5 DATE_TRUNC('month', event_time) AS month_start,
6 DATE_TRUNC('year', event_time) AS year_start
7FROM event_data
Result
event_timeday_startweek_startmonth_startyear_start
2024-01-15 14:32:182024-01-15 00:00:002024-01-15 00:00:002024-01-01 00:00:002024-01-01 00:00:00

DATE_TRUNC sets all smaller units to their minimum value. Truncating to month sets day to 1 and time to 00:00:00.

Grouping by Time Period

Combine DATE_TRUNC with GROUP BY to create time-series aggregations.

1SELECT
2 DATE_TRUNC('month', order_date) AS month,
3 COUNT(*) AS order_count,
4 SUM(revenue) AS total_revenue
5FROM orders
6GROUP BY DATE_TRUNC('month', order_date)
7ORDER BY month
Result
monthorder_counttotal_revenue
2024-01-01 00:00:00152342150.00
2024-02-01 00:00:00168748320.50
2024-03-01 00:00:00184251200.75

Week Starts

Weeks can start on Sunday or Monday depending on locale. DATE_TRUNC('week', ...) typically uses Monday. Check your database documentation.

01
Hour
GROUP BY hourly trends
02
Day
Daily summaries and reports
03
Week
Weekly performance metrics
04
Month
Monthly revenue tracking
05
Quarter
Quarterly financial reports
06
Year
Annual comparisons

> Group orders by week and count how many per week.

SELECT
  ___(___, order_date) AS week,
  ___ AS order_count
FROM orders
GROUP BY DATE_TRUNC('week', order_date)
DATE_TRUNC
EXTRACT
COUNT(*)
'week'

DATE_TRUNC is preferred over EXTRACT for grouping because the truncated value is a valid timestamp that sorts and displays naturally. EXTRACT returns a plain integer that loses date context.

The truncated timestamp also works as an X-axis value in charts without additional formatting, making it ideal for time-series visualizations in BI tools.

For fiscal calendars that do not align with standard weeks or months, DATE_TRUNC to day followed by custom interval arithmetic provides the necessary flexibility.

Parsing and Formatting

Daily Life
Interviews

Read and write dates in any format

Different systems use different date formats. APIs might send "2024-01-15T10:30:00Z" while CSV files contain "01/15/2024". SQL provides functions to parse strings into timestamps and format timestamps into strings.

Parsing Strings to Dates

Use DATE_PARSE to convert formatted strings into timestamps.

1SELECT
2 DATE_PARSE(
3 '2024-01-15 10:30:00',
4 'yyyy-MM-dd HH:mm:ss'
5 ) AS parsed_date,
6 DATE_PARSE(
7 '01/15/2024',
8 'MM/dd/yyyy'
9 ) AS us_format,
10 DATE_PARSE(
11 '15-01-2024',
12 'dd-MM-yyyy'
13 ) AS eu_format
Result
parsed_dateus_formateu_format
2024-01-15 10:30:002024-01-15 00:00:002024-01-15 00:00:00
Format codes: yyyy=year, MM=month, dd=day, HH=hour, mm=minute, ss=second.

Formatting Dates to Strings

Use DATE_FORMAT to convert timestamps into formatted strings for display or export.

1SELECT
2 order_date,
3 DATE_FORMAT(
4 order_date,
5 'yyyy-MM-dd'
6 ) AS iso_date,
7 DATE_FORMAT(order_date, 'MM/dd/yyyy') AS us_date,
8 DATE_FORMAT(
9 order_date,
10 'dd MMM yyyy'
11 ) AS readable
12FROM orders
Result
order_dateiso_dateus_datereadable
2024-01-15 10:30:002024-01-1501/15/202415 Jan 2024

ISO 8601 Format

ISO 8601 (YYYY-MM-DD) is the international standard. Use it for APIs and file interchange to avoid ambiguity.
TIP
US format (MM/DD/YYYY) and European format (DD/MM/YYYY) are ambiguous. Always use ISO 8601 for storage and APIs.

Common Format Patterns

yyyy-MM-ddyyyy-MM-dd HH:mm:ssMM/dd/yyyydd/MM/yyyyMMM dd, yyyy
yyyy-MM-dd
ISO 8601 Date
Output: 2024-01-15
yyyy-MM-dd HH:mm:ss
ISO Datetime
Output: 2024-01-15 10:30:45
MM/dd/yyyy
US Format
Output: 01/15/2024
dd/MM/yyyy
EU Format
Output: 15/01/2024
MMM dd, yyyy
Readable
Output: Jan 15, 2024

> Format order_date as a readable string like "Jan 15, 2024".

SELECT
  ___(
    order_date,
    ___
    ) AS formatted
FROM orders
'MMM dd, yyyy'
DATE_PARSE
'yyyy-MM-dd'
DATE_FORMAT

DATE_FORMAT output is a string, not a timestamp. Once formatted, the value cannot be used for date arithmetic or comparisons without parsing it back. Format only at the final output stage.

Always store timestamps in native date types and use DATE_FORMAT exclusively in SELECT for display. Storing pre-formatted strings prevents any future date calculations.

The MMM abbreviation for month names may be locale-dependent. For cross-regional systems, use numeric formats like yyyy-MM-dd to avoid language differences in output.

ISO 8601 Functions

Daily Life
Interviews

Work with standard date representations

ISO 8601 is the international standard for date and time representation. It uses the format YYYY-MM-DDTHH:MM:SS with optional timezone offset. Most modern APIs use ISO 8601, making dedicated parsing and formatting functions essential for integration work.

FROM_ISO8601_TIMESTAMP parses ISO 8601 strings to timestamps. TO_ISO8601 formats timestamps as ISO 8601 strings. These specialized functions handle the nuances of the standard, including the 'T' separator and timezone suffixes.

Understanding ISO 8601

ISO 8601 Format Examples
  • 2024-03-15: Date only
  • 2024-03-15T14:30:45: Date and time
  • 2024-03-15T14:30:45Z: UTC timezone
  • 2024-03-15T14:30:45+05:30: With offset
The 'T' separates date from time. 'Z' indicates UTC (Zulu time). Numeric offsets like +05:30 indicate hours and minutes from UTC. ISO 8601 is unambiguous and globally understood.

Parsing ISO 8601 Dates

1SELECT
2 iso_string,
3 FROM_ISO8601_TIMESTAMP(
4 iso_string
5 ) AS parsed_timestamp
6FROM api_calls
Result
iso_stringparsed_timestamp
2024-03-15T14:30:45Z2024-03-15 14:30:45 UTC
2024-03-15T10:00:00-04:002024-03-15 14:00:00 UTC
2024-03-15T23:30:00+09:002024-03-15 14:30:00 UTC

FROM_ISO8601_TIMESTAMP handles timezone offsets automatically, normalizing to UTC. The string '2024-03-15T10:00:00-04:00' (10 AM Eastern, 4 hours behind UTC) becomes 14:00 UTC.

//

Formatting to ISO 8601

1SELECT
2 FROM_ISO8601_TIMESTAMP(
3 '2024-03-15T14:30:45Z'
4 ) AS parsed

API Integration Patterns

1SELECT
2 order_id,
3 FROM_ISO8601_TIMESTAMP(
4 api_created_at
5 ) AS created_timestamp,
6 TO_ISO8601(processed_at) AS api_processed_at
7FROM order_processing
Result
order_idcreated_timestampapi_processed_at
10012024-03-15 14:30:45 UTC2024-03-15T14:45:00.000Z
10022024-03-15 15:00:00 UTC2024-03-15T15:12:30.000Z
Incoming timestamps are parsed and stored as native timestamp types for efficient querying. Outgoing timestamps are formatted back to ISO 8601 for API compatibility.
//

ISO 8601 Function Uses

ISO 8601 is the universal standard for timestamp exchange between systems.
REST APIs
REST APIs
Parse incoming timestamps and format outgoing responses
Data exchange
Data exchange
Universal format for cross-system data transfer
Event logging
Event logging
Standard format for audit trails and log files

> Parse ISO 8601 timestamp strings from API call records.

SELECT
  ___(
    ___
    ) AS parsed_timestamp
FROM api_calls
PARSE_DATETIME
call_time
TO_ISO8601
FROM_ISO8601_TIMESTAMP

FROM_ISO8601_TIMESTAMP normalizes all timezone offsets to UTC automatically. After parsing, every timestamp is comparable regardless of the original offset in the API string.

ISO 8601 parsing is stricter than DATE_PARSE. It expects exact compliance with the standard format, so malformed strings from unreliable sources should be validated before parsing.

Pairing FROM_ISO8601_TIMESTAMP with TO_ISO8601 creates a clean round-trip: parse incoming API timestamps to UTC, do all calculations natively, then format back for the response.

DATE_FORMAT()

Daily Life
Interviews

Display dates exactly how users expect

DATE_FORMAT converts timestamps to formatted strings for export, display, or downstream systems. While PARSE_DATETIME brings data in, DATE_FORMAT sends it out in exactly the format consumers require.

Format patterns control how timestamps appear in output. Each letter represents a specific component:
1SELECT
2 DATE_FORMAT(
3 created_at,
4 'MM/dd/yyyy hh:mm a'
5 ) AS us_format
6FROM orders
US format with 12-hour clock and AM/PM. European format with 24-hour clock. Compact format for filenames and sorting - no separators, lexicographically sortable.

Output for Reports

Reports often need human-readable dates with full month names:
1SELECT
2 DATE_FORMAT(
3 sale_date,
4 'MMMM dd, yyyy'
5 ) AS report_date,
6 DATE_FORMAT(sale_date, 'EEEE') AS day_of_week,
7 total_amount
8FROM daily_sales
Result
report_dateday_of_weektotal_amount
March 15, 2024Friday12450.00
March 16, 2024Saturday18320.00
'%M' gives the full month name. '%W' gives the full weekday name. These patterns make dates immediately readable without mental conversion.

API and File Output

For API responses and file exports, use TO_ISO8601 or DATE_FORMAT with ISO patterns:

1SELECT
2 order_id,
3 TO_ISO8601(created_at) AS api_timestamp,
4 DATE_FORMAT(
5 created_at,
6 'yyyy-MM-dd'
7 ) AS file_date
8FROM orders
Result
order_idapi_timestampfile_date
10012024-03-15T14:30:00.000Z2024-03-15
10022024-03-16T09:15:00.000Z2024-03-16
ISO 8601 is the standard for cross-system data exchange. The Z suffix indicates UTC timezone.

> Format order timestamps as ISO 8601 strings for an API response.

SELECT
  order_id,
  ___(___) AS api_timestamp
FROM orders
created_at
FROM_ISO8601_TIMESTAMP
DATE_FORMAT
TO_ISO8601

TO_ISO8601 always outputs the Z suffix indicating UTC. If your database stores timestamps in a non-UTC timezone, convert to UTC first using AT TIME ZONE before calling TO_ISO8601.

The millisecond precision in TO_ISO8601 output (.000Z) is part of the standard. Consuming systems should handle it, but if a downstream API rejects milliseconds, use DATE_FORMAT with a custom pattern instead.

Mastering timezone conversions, truncation, and formatting prepares you for global applications. Practice these patterns to build robust date handling logic.
PUTTING IT ALL TOGETHER

> You are a data engineer at Wise building a global payments dashboard that must show transaction volumes in each user's local timezone, truncated to daily and weekly periods, and export timestamps as ISO 8601 strings for downstream API consumers.

AT TIME ZONE converts every UTC transaction timestamp to the payer's local timezone before aggregation.
DATE_TRUNC() groups converted timestamps into day and week buckets for the volume trend chart.
DATE_FORMAT() and DATE_PARSE() handle inbound webhook timestamps that arrive as regional string formats.
TO_ISO8601() produces the standardized export strings that downstream payment APIs and partners require.
KEY TAKEAWAYS
Always store timestamps in UTC; convert to local timezone only for display
AT TIME ZONE converts between timezones without losing information
DATE_TRUNC groups timestamps into periods (hour, day, week, month, year)
Use ISO 8601 format (YYYY-MM-DD) for unambiguous date interchange
DATE_FORMAT converts timestamps to formatted strings for display
DATE_PARSE converts formatted strings to timestamps for processing
FROM_ISO8601_TIMESTAMP and TO_ISO8601 handle the ISO 8601 standard format

Timezones, truncation, and global time handling

Category
SQL
Difficulty
advanced
Duration
24 minutes
Challenges
0 hands-on challenges

Topics covered: Timezone Control, DATE_TRUNC(), Parsing and Formatting, ISO 8601 Functions, DATE_FORMAT()

Lesson Sections

  1. Timezone Control

    Timestamps without timezone context are ambiguous. "2024-01-15 10:00:00" could be UTC, Pacific, or any timezone. SQL provides functions to attach timezone information and convert between zones. Timezone Types Converting Timezones The same instant appears differently in each timezone. Tokyo is 9 hours ahead of UTC, so 10:00 UTC becomes 19:00 Tokyo. Time Across Multiple Zones For real-time dashboards, show current time in each region where users operate. Daylight Saving Time DST adds complexity. I

  2. DATE_TRUNC() (concepts: sqlDateTrunc)

    Truncating to Common Units Truncate to day, week, month, or year to group timestamps into buckets for aggregation. Grouping by Time Period Week Starts The truncated timestamp also works as an X-axis value in charts without additional formatting, making it ideal for time-series visualizations in BI tools.

  3. Parsing and Formatting (concepts: sqlDateFormat)

    Different systems use different date formats. APIs might send "2024-01-15T10:30:00Z" while CSV files contain "01/15/2024". SQL provides functions to parse strings into timestamps and format timestamps into strings. Parsing Strings to Dates Format codes: yyyy=year, MM=month, dd=day, HH=hour, mm=minute, ss=second. Formatting Dates to Strings ISO 8601 Format ISO 8601 (YYYY-MM-DD) is the international standard. Use it for APIs and file interchange to avoid ambiguity. Common Format Patterns The MMM a

  4. ISO 8601 Functions

    ISO 8601 is the international standard for date and time representation. It uses the format YYYY-MM-DDTHH:MM:SS with optional timezone offset. Most modern APIs use ISO 8601, making dedicated parsing and formatting functions essential for integration work. Understanding ISO 8601 The 'T' separates date from time. 'Z' indicates UTC (Zulu time). Numeric offsets like +05:30 indicate hours and minutes from UTC. ISO 8601 is unambiguous and globally understood. Parsing ISO 8601 Dates Formatting to ISO 8

  5. DATE_FORMAT()

    Format patterns control how timestamps appear in output. Each letter represents a specific component: US format with 12-hour clock and AM/PM. European format with 24-hour clock. Compact format for filenames and sorting - no separators, lexicographically sortable. Output for Reports Reports often need human-readable dates with full month names: '%M' gives the full month name. '%W' gives the full weekday name. These patterns make dates immediately readable without mental conversion. API and File O