How to convert a column in a table to date format for plotting a time series?

44 ビュー (過去 30 日間)
Tom Kristian Hoffmann
Tom Kristian Hoffmann 2020 年 12 月 9 日
回答済み: Eric Sofen 2020 年 12 月 11 日
Dear MATLAB friends
I´m struggling with the conversion of a column to the date format. The cells in the row are written as '2012-09-01T00:00:00.000Z' . I want to convert all the cells in the column to dates that I can use for plotting a time series.
Any handy hints for this issue?
Thank you already in advance!
Regards
Tom

採用された回答

Harry Laing
Harry Laing 2020 年 12 月 9 日
You can use the datetime function to convert from string to datetime format for plotting. However, the letter T and Z in your string may give you a headache here.
Either manually or via writing a script, replace the T with a space, and remove the Z, then you can send the entire column of data to the datetime function like so:
datetime(Column_of_Time_Strings,'InputFormat','yyyy-MM-dd HH:mm:ss.SSS')
e.g.
datetime('2012-09-01 00:00:00.000','InputFormat','yyyy-MM-dd HH:mm:ss.SSS')
ans=
datetime
01-Sep-2012 00:00:00
Assuming all your time strings in the column follow the same format with a letter T and Z, you could use something like the function strrep to replace parts of the string like so:
newStr = strrep('2012-09-01T00:00:00.000Z', 'T', ' ') % This replaces T with a space
newStr = strrep(newStr, 'Z', '') % This replaces Z with no space (nothing)
  1 件のコメント
Tom Kristian Hoffmann
Tom Kristian Hoffmann 2020 年 12 月 10 日
Hey Harry,
thank you so much for your fast help! Replacing the letters with space/nothing and then converting the strings to datetime format 'yyyy-MM-dd HH:mm:ss' was succesfull!

サインインしてコメントする。

その他の回答 (1 件)

Eric Sofen
Eric Sofen 2020 年 12 月 11 日
There's no need to replace the 'T' and 'Z' literals. Datetime formats can include literals:
datetime(Column_of_Time_Strings,'InputFormat',"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by