Reputation: 1634
I am wondering what the best way to convert date time format "1/22/20" into "2020-01-22". I tried DateTime.(d1.date, "m/d/y")
and I feel I was missing something in the output. Any suggestion?
julia> first(d1, 10)
10×2 DataFrame
Row │ date value
│ String Int64
─────┼────────────────
1 │ 1/22/20 1
2 │ 1/23/20 1
3 │ 1/24/20 2
4 │ 1/25/20 2
5 │ 1/26/20 5
6 │ 1/27/20 5
7 │ 1/28/20 5
8 │ 1/29/20 6
9 │ 1/30/20 6
10 │ 1/31/20 8
julia> DateTime.(d1.date, "m/d/y")
519-element Vector{DateTime}:
0020-01-22T00:00:00
0020-01-23T00:00:00
0020-01-24T00:00:00
0020-01-25T00:00:00
0020-01-26T00:00:00
0020-01-27T00:00:00
0020-01-28T00:00:00
0020-01-29T00:00:00
0020-01-30T00:00:00
0020-01-31T00:00:00
0020-02-01T00:00:00
0020-02-02T00:00:00
0020-02-03T00:00:00
Upvotes: 3
Views: 473
Reputation: 13820
The DateTime
constructor converts a string to a datetime. To convert back to a string (of a different format), use Dates.format
:
Dates.format.(DateTime.(d1.date, dateformat"m/d/y"), dateformat"yyyy-mm-dd")
Since your years only have two digits, they're interpreted as year 20 instead of 2020. To fix this, you can add Dates.Year(2000)
to the dates.
Dates.format.(DateTime.(d1.date, dateformat"m/d/y") .+ Dates.Year(2000), dateformat"yyyy-mm-dd")
You should make sure to use the @dateformat_str
macro to construct DateFormat
s whenever possible because the conversion of String
to DateFormat
is quite expensive, and using a macro to do it means it happens a single time, at compilation time (when the macro is expanded) instead of once per DataFrame row.
Upvotes: 3