Using Date and Time Functions in Julia
Overview 1
Dates
is a module that collects functions related to dates and times. It is inevitably useful not only for general programming but also for handling a lot of data, whether it’s related to time series or not1.
Code
Full Code
using Dates
오늘 = DateTime(2022,3,10)
typeof(오늘)
propertynames(오늘)
오늘.instant
myformat = DateFormat("d-m-y")
내일 = Date("11-3-2022", myformat)
Dates.dayname(내일)
일주일뒤까지 = 오늘:Day(1):DateTime(2022,3,17)
collect(일주일뒤까지)
Dates.Day(일주일뒤까지[end]) - Dates.Day(오늘)
DateTime
Type
julia> 오늘 = DateTime(2022,3,10)
2022-03-10T00:00:00
julia> typeof(오늘)
DateTime
For instance, if you assigned the date of March 10th of the year 22 to today
using the DateTime()
function, then today
would have the type DateTime
. DateTime
has a property called instant
, which records time in milliseconds.
julia> propertynames(오늘)
(:instant,)
julia> 오늘.instant
Dates.UTInstant{Millisecond}(Millisecond(63782553600000))
Format DateFormat()
julia> myformat = DateFormat("d-m-y")
dateformat"d-m-y"
julia> 내일 = Date("11-3-2022", myformat)
2022-03-11
This is often used when dates are written differently due to the difference between the East and the West.
Day of the Week Dates.dayname()
julia> Dates.dayname(내일)
"Friday"
Returns the day of the week for the given date. Due to the absurdity of the Gregorian calendar, creating such a function myself would be surprisingly difficult.
Vector of Dates
julia> 일주일뒤까지 = 오늘:Day(1):DateTime(2022,3,17)
DateTime("2022-03-10T00:00:00"):Day(1):DateTime("2022-03-17T00:00:00")
julia> collect(일주일뒤까지)
8-element Vector{DateTime}:
2022-03-10T00:00:00
2022-03-11T00:00:00
2022-03-12T00:00:00
2022-03-13T00:00:00
2022-03-14T00:00:00
2022-03-15T00:00:00
2022-03-16T00:00:00
2022-03-17T00:00:00
This is arguably the most useful part of the Julia date package. Vectorizing the span between specific points in time as above results in exactly what you would imagine. It’s challenging to create, but it’s rare to find syntax in other languages that integrates so well and provides such outstanding intuition.
Date Subtraction -
julia> Dates.Day(일주일뒤까지[end]) - Dates.Day(오늘)
7 days
Apparently, you can calculate the interval between two points in time with subtraction. Using Dates.canonicalize()
allows for pretty output in hours, minutes, and seconds.
Environment
- OS: Windows
- julia: v1.7.0