Reputation: 55
I have an Excel 2016 file with several tables that I have joined together using Power Query. The tables have some date fields that are populated as text (e.g. "1022018" = Jan 2, 2018) and I need to convert them to dates. I added a column for each that converts the data just fine but every time I refresh my query, the new columns disappear.
I opened Power Query and tried adding a custom column but the formula I created in Excel does not work and it needs to be written in M. I haven't had any luck finding an easy conversion to M or another way to create the columns using the Excel formula.
Any ideas how to accomplish this?
FYI here is formula: =IF(LEN([@DOBstring])=7,DATE(RIGHT([@DOBstring],4),LEFT([@DOBstring],1),MID([@DOBstring],2,2)),DATE(RIGHT([@DOBstring],4),LEFT([@DOBstring],2),MID([@DOBstring],3,2)))
Upvotes: 0
Views: 572
Reputation: 4486
If I've understood correctly, the month
in the input string isn't zero-padded (causing input strings to be of length either 7 or 8).
It might be worth creating a small function like the below, which will handle the varying length and then attempt to parse a date based on assumed character positions.
ParseDate = (someText as text) as date =>
let
zeroPadded = Text.End("0" & someText, 8),
yearParsed = Text.End(zeroPadded, 4),
monthParsed = Text.Start(zeroPadded, 2),
dayParsed = Text.Middle(zeroPadded, 2, 2),
dateParsed = #date(Number.From(yearParsed), Number.From(monthParsed), Number.From(dayParsed))
in dateParsed,
You can then invoke it when transforming an existing column, or adding a new column. To give you an example:
let
ParseDate = (someText as text) as date =>
let
zeroPadded = Text.End("0" & someText, 8),
yearParsed = Text.End(zeroPadded, 4),
monthParsed = Text.Start(zeroPadded, 2),
dayParsed = Text.Middle(zeroPadded, 2, 2),
dateParsed = #date(Number.From(yearParsed), Number.From(monthParsed), Number.From(dayParsed))
in dateParsed,
someTable = Table.FromColumns({{"1022018", "05242019", "12282026"}}, type table [toParse = text]),
transformedColumn = Table.TransformColumns(someTable, {{"toParse", ParseDate, type date}}),
addedColumn = Table.AddColumn(someTable, "parsed", each ParseDate([toParse]), type date)
in
addedColumn
which gives:
Upvotes: 1
Reputation: 51
In Power Query, create a custom column with the following formula:
= if Text.Length([Date])=7 then
Text.Middle([Date],1,2)
& "-"
& "0"
& Text.Start([Date], 1)
& "-"
& Text.End([Date],4)
else
Text.Middle([Date],2,2)
& "-"
& Text.Start([Date], 2)
& "-"
& Text.End([Date],4)
This will result in a text with the format dd-mm-yyyy. Depending on your regional settings, this would then be converted to a correct date value when formatting this custom column as date.
Otherwise, you would need this formula:
= if Text.Length([Date])=7 then
"0"
& Text.Start([Date], 1)
& "-"
& Text.Middle([Date],1,2)
& "-"
& Text.End([Date],4)
else
Text.Start([Date], 2)
& "-"
& Text.Middle([Date],2,2)
& "-"
& Text.End([Date],4)
Upvotes: 0