简体   繁体   中英

converting yyyy-mm-dd hh:mm:ss.ms to yyyy-mm-dd hh:mm:ss using matlab

I received timestamp datasets which are in the format of yyyy-mm-dd HH:MM:SS.ms . I want to convert into yyyy-mm-dd HH:MM:SS format. Is there any way to select only in this format using matlab?

For example:

2012-08-01 00:10:00.0

should be:

2012-08-01 00:10:00

Please note that the millisecond values are all zero.

The general way would be to use datestr to convert it to your desired format.

dates = {'2012-08-01 00:10:00.1';
         '2012-08-01 00:10:00.1'};

new = datestr(dates, 'yyyy-mm-dd HH:MM:SS');
%   2012-08-01 00:10:00
%   2012-08-01 00:10:00

Another approach would be that since all of your milliseconds are going to be zero (therefore you don't have to worry about rounding) you can just use a regular expression to remove the milliseconds component (anything after the decimal point)

new = regexprep(dates, '\..*', '')

This is likely going to be more performant as you don't need to perform the intermediate step of converting to either a datetime object or a date number.

Since the input and output format are the same except for the milliseconds, don't use date functions, but simple string operations:

% example dates
C = {'2012-08-01 00:10:00.0'
     '2013-08-02 00:11:11.0'
     '2014-08-03 00:12:22.0'
     '2015-08-04 00:13:33.0'
     '2016-08-05 00:14:44.0'};

% method 1
D = cellfun(@(x)x(1:end-2), C, 'UniformOutput', false);

% method 2 (same, but no cellfun)
D = char(C);
D = cellstr(D(:,1:end-2));

% method 3
D = regexp(C, '[^\.]*', 'match', 'once');

% method 4
D = regexprep(C, '\..*$', '');

Lets say you need this data in datetime objects anyway then i would do something like this:

inp = {'2012-08-01 00:10:00.0'; '2012-08-02 04:10:00.0'}; % Some datestrins
t = datetime(inp,'InputFormat','yyyy-MM-dd HH:mm:ss.0'); % Convert to datetimes
datestr(t, 'yyyy-mm-dd HH:MM:SS') % convert back to strings

For the input & output formatter see the documentation. I assume that the last part is always zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM