Cast/parse multiple variables at once


Having to process dates read from files, I’m currently doing e.g.:

yyyy, mm, dd, h, m, s = parse(Int32, date[1:4]), parse(Int32, date[5:6]), parse(Int32, date[7:8]), parse(Int32, date[9:10]), parse(Int32, date[11:12]), parse(Int32, date[13:14])
date_julia=DateTime(yyyy, mm, dd, h, m, s)

I would like to know if there’s a way to do a grouped cast like:

parse(Int32; yyyy, mm, dd, h, m, s)

Or maybe there’s a way to extract the date directly from the string (or int), but I’ve seen none in the documentation.

If you use CSV.jl to read the data from file there is parameter dateformat

1 Like

Does parse.(Int32, (yyyy, mm, dd, h, m, s)) or parse.(Ref(Int32), (yyyy, mm, dd, h, m, s)) work?

Also pretty sure you can give DateTime the string format and it will parse the string for you, but don’t remember the API for that.

1 Like

You can directly create a DateTime from a string specifying the format:

julia> using Dates

julia> format = dateformat"yyyymmddHHMMSS"

julia> DateTime("20240516235400", format)

Nils provided the solution, but note that you could broadcast the parsing command across an array of index ranges:

using Dates
date = "20240516235400"
ix = [1:4, 5:6, 7:8, 9:10, 11:12, 13:14]
yyyy,mm,dd,h,m,s = parse.(Int32, getindex.(date, ix))
date_julia = DateTime(yyyy,mm,dd,h,m,s)

Thanks everyone, there’s many ways to proceed.