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
Convert times across global time 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.
- No timezone info
- Ambiguous across regions
- Assumes local time
- Use for: birth dates, deadlines
- Stores UTC + offset
- Unambiguous globally
- Converts for display
- Use for: events, API timestamps
Converting Timezones
Use AT TIME ZONE to convert timestamps between timezones.
Time Across Multiple Zones
Daylight Saving Time
> Convert a UTC timestamp to Pacific timezone.
SELECT event_timestamp AS pacific_time FROM event_data
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.
DATE_TRUNC()
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
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.
Week Starts
Weeks can start on Sunday or Monday depending on locale. DATE_TRUNC('week', ...) typically uses Monday. Check your database documentation.
> 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 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.
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
Read and write dates in any format
Parsing Strings to Dates
Use DATE_PARSE to convert formatted strings into timestamps.
Formatting Dates to Strings
Use DATE_FORMAT to convert timestamps into formatted strings for display or export.
ISO 8601 Format
Common Format Patterns
> Format order_date as a readable string like "Jan 15, 2024".
SELECT ( order_date, ) AS formatted FROM orders
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.
ISO 8601 Functions
Work with standard date representations
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
- 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
Parsing ISO 8601 Dates
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
API Integration Patterns
ISO 8601 Function Uses
> Parse ISO 8601 timestamp strings from API call records.
SELECT ( ) AS parsed_timestamp FROM api_calls
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()
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.
Output for Reports
API and File Output
For API responses and file exports, use TO_ISO8601 or DATE_FORMAT with ISO patterns:
> Format order timestamps as ISO 8601 strings for an API response.
SELECT order_id, () AS api_timestamp FROM orders
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.
> 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.AT TIME ZONE converts between timezones without losing informationDATE_TRUNC groups timestamps into periods (hour, day, week, month, year)DATE_FORMAT converts timestamps to formatted strings for displayDATE_PARSE converts formatted strings to timestamps for processingFROM_ISO8601_TIMESTAMP and TO_ISO8601 handle the ISO 8601 standard formatTimezones, 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
- 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
- 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.
- 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
- 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
- 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