Hello, how can I make this code more optimal?
import Dates
const Unixtime = Int
function unix2yyyymmdd(unixtime::Unixtime)::Int
datetime = Dates.unix2datetime(unixtime)
date = floor(datetime, Dates.Day)
str = Dates.format(date, "yyyymmdd")
return Meta.parse(str)
end
@time unix2yyyymmdd(123) # -> 0.000123 seconds (38 allocations: 1.805 KiB)
Well instead of parsing you could just use arithmetic on the parts (see accessors here: Dates · The Julia Language)
So something like:
julia> d = Date(2023, 9, 1)
julia> 10^4*d.year + 10^2*d.month + d.day
1 Like
oheil
3
function unix2yyyymmdd(unixtime::Unixtime)::Int
Meta.parse(Dates.unix2datetime(unixtime) |> d -> floor(d, Dates.Day) |> d->Dates.format(d,dateformat"yyyymmdd"))
end
@time unix2yyyymmdd(123)
0.000090 seconds (17 allocations: 664 bytes)
19700101
1 Like
lbilli
4
using Dates
function u2ymd(unixtime)
y, m, d = yearmonthday(unix2datetime(unixtime))
10000y + 100m + d
end
u2ymd(123)
19700101
4 Likes