Problem of saving time format

2 次查看(过去 30 天)
Mekala balaji
Mekala balaji 2016-2-18
回答: BhaTTa 2024-7-24
I have the following data:
Index Time Name
1 2015/2/6 23:34:24 Pr.VBN.12K
2 2015/2/7 22:34:24 Pr.VBN.13K
3 2015/2/8 22:56:24 Pr.VBN.14K
I want to read and write to csv. I sue the following code:
clc;
clear all;
close all
[~, ~, data]=xlsread('referenceData.xlsx');
xlswrite('test.csv',data);
But when I save to csv my time format is changing, kindly help how to do this.
Index Time Name
1 2015/2/6 下午 11:34:24 Pr.VBN.12K
2 2015/2/7 下午 10:34:24 Pr.VBN.13K
3 2015/2/8 下午 10:56:24 Pr.VBN.14K
Many thanks in advance.
Sincerely,

回答(1 个)

BhaTTa
BhaTTa 2024-7-24
You can use the 'readtable' and 'writetable' functions, which provide better control over the data types and formats.
Here's how you can read the data from an Excel file and write it to a CSV file while preserving the datetime format:
clc;
clear all;
close all;
% Read data from Excel file
data = readtable('referenceData.xlsx');
% Convert the 'Time' column to datetime if necessary
% Assuming 'Time' is already in datetime format, otherwise use:
% data.Time = datetime(data.Time, 'InputFormat', 'yyyy/MM/dd HH:mm:ss');
% Write data to CSV file
writetable(data, 'test.csv');
Explanation
  1. Read Data from Excel File: Use the readtable function to read the data from the Excel file into a table. This function automatically detects and preserves the data types, including datetime.
  2. Convert 'Time' Column to Datetime: If the 'Time' column is not already in datetime format, you can convert it using the datetime function. Adjust the InputFormat parameter as necessary to match your input format.
  3. Write Data to CSV File: Use the writetable function to write the table to a CSV file. This function preserves the datetime format when writing to the file.
By using 'readtable' and 'writetable', you ensure that the datetime format is preserved correctly when reading from and writing to the files. Adjust the InputFormat parameter if your datetime data has a different format.

标签

Community Treasure Hunt

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

Start Hunting!

Translated by