Convert Union{Missing, String31} to DateTime

I have dataframe with a column which has some string values and some missing values. I wanted to convert this column into a DataTime column.
I have used the following code
df.dt = DateTime.(df.dt, dateformat"yyyy-mm-dd HH:MM:SS")

I am getting a MethodError: no method matching Int64(::Vector{Union{Missing, String31}})

Does

using Missings, Date, DataFrames
df.dt = passmissing(DateTime).(df.dt, dateformat"yyyy-mm-dd HH:MM:SS")

work for you?
Typing ?passmissing in the REPL will give you the corresponding help.

You can use TidierDates.jl which leverages (and rexports) Dates.jl and will returning missing where a vector has a missing entry

using TidierDates
ymd_hms.(DF.col)
ymd_hms("2023-06-15 09:30:00")
2023-06-15T09:30:00

It seems to me your problem is something else, what’s eltyp(df.dt)?

If you just had missing you’d get:

julia> DateTime.(["2020-01-01 00:00:00", missing], dateformat"yyyy-mm-dd HH:MM:SS")
ERROR: MethodError: no method matching Int64(::Missing)

but it appears you have vectors inside your vector, because your error message is:

julia> DateTime.(["2020-01-01 00:00:00", ["a", missing]], "yyyy-mm-dd HH:MM:SS")
ERROR: MethodError: no method matching Int64(::Vector{Union{Missing, String}})

so you need to figure out where those vectors come from, and then you can do passmissing as Rudi suggests once you’ve isolated the missings to scalar values.

1 Like