ClickhouseMark NeedhamTutorial
5 ways to parse Dates and DateTimes in ClickHouse
Summary
ClickHouse provides several ways to convert dates and datetimes from Unix timestamps, packed numeric values, known-format strings, mixed inputs, and file data. The examples use fromUnixTimestamp and its millisecond and microsecond variants, YYYYMMDDToDate and YYYYMMDDhhmmssToDateTime, plus parseDateTime or parseDateTimeInJodaSyntax when the input format is known. For unknown or mixed formats, parseDateTimeBestEffort and its DateTime64 counterpart accept inputs such as ISO 8601 strings, dates, and timestamp strings; invalid values otherwise raise an exception, while OrNull returns NULL and OrZero returns January 1, 1970 at midnight. The post also shows direct ::DateTime casting, controlled by cast_string_to_date_time_mode: basic supports standard forms, whereas best_effort broadens parsing but still throws for completely invalid dates. An inline or session setting lets the same casting approach parse rows from a CSV file.
Context
Dates may arrive as Unix timestamps from event streams, packed numeric values in legacy exports or mainframe flat files, formatted strings from APIs, or mixed values in a file. The post addresses both known and unknown date formats, including invalid input handling.
Approach / What changed
Use explicit ClickHouse conversion functions for Unix timestamps, packed dates, and known formats; use the parseDateTimeBestEffort family for mixed or unknown formats; or cast strings directly to DateTime after configuring cast_string_to_date_time_mode as basic or best_effort. The examples include NULL and zero fallbacks and CSV input.
Takeaways
fromUnixTimestamp returns DateTime, while fromUnixTimestamp64Milli and fromUnixTimestamp64Micro return DateTime64(3) and DateTime64(6), respectively.
parseDateTimeBestEffort64 throws on completely invalid input; its OrNull variant returns NULL, and its OrZero variant returns January 1, 1970 at midnight.
cast_string_to_date_time_mode defaults to basic; setting it to best_effort enables broader formats, but completely invalid dates still cause an exception.
Source and freshness
- Source
- clickhouse.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.