How to Parse Date or Time in multiple possible format?

My user upload a CSV file with “Time” column
Sometimes could be HHMMSS, sometimes could be HH:MM:SS, sometimes could be other format, like HHMM.

How can I read the CSV file and automatically convert the “Time” column to a Time object?

Can I parse it with something like: " HHMMSS|HH:MM:SS " → this is doable in C#.

you can remove : from all entries beforehand

or
a try block using these:

date_object = try
        Date(blah, dateformat"HH:MM:SS")
    catch
        Date(blah, dateformat"HHMMSS")
    end

First, I don’t think this gives the desired result, eg

julia> Date("09:01:02", dateformat"HH:MM:SS")
0001-01-01

It would be better to use Time.

Second, I think that try ... catch is not recommended for use like this because it may be slow. It would be better to just test the string for :. Eg something like

using Dates
function robust_time_parse(str)
    if any(isequal(':'), str)
        Time(str, dateformat"HH:MM:SS")
    else
        Time(str, dateformat"HHMMSS")
    end
end
robust_time_parse("090101")
robust_time_parse("09:01:01")
1 Like

ah, right, Date only handles dates, of course. well but op also mentioned

so maybe also check length? this all depends on how regulated the user input is (which should be done at the front end)

Thank you, but there maybe some other cases, like HHMM, HHMMSS. milisecond, or any other format.
Ideally i want to have a generic solution, just like in C#, that I can do “xxx|yyy|zzz”.

Where Can I request such a feature to Julia developer?

Thank you

There is nothing preventing you from doing this, but since this is just a simple programming exercise, I think you should just implement it.

For the general case, you will find tryparse helpful.

2 Likes