简体   繁体   中英

Change format of date column in CSV

I have CSV file with the following format

Column_a,Column_b,Column_c,Column_date
a,b,c,08-jun-2017 00:00 to UP (ENG)

I want to convert the data with name Column_date

Example: 08-jun-2017 00:00 to UP (ENG) should be converted to 17W23D4 to UP (ENG)

The format is year within century 17 ; week of year W23 ; day of week D4 . The days go from Monday (1) to Sunday (7).

So the final CSV should look like:

Column_a,Column_b,Column_c,Column_date
a,b,c,17W23D4 to UP (ENG)

It would be great if can do in a .bat file, but another scripting language is also okay.

In Perl, you can use Time::Piece :

$ perl -MTime::Piece -wE '
    $tp = Time::Piece->strptime("08-jun-2017 00:00", "%d-%b-%Y %H:%M");
    say $tp->yy, "W", $tp->week, "D", $tp->day_of_week'
17W23D4

You first need to extract the date and time from the string, though.

You can use -F, to split each line on commas into the @F array, then use a regex to extract the timestamp:

perl -MTime::Piece -F, -anE '
    print, next if $. == 1;
    ($timestring, $rest)
        = pop(@F) =~ /([0-9]{2}-[a-z]{3}-[0-9]{4} [0-9]{2}:[0-9]{2})(.*)/;
    $tp = Time::Piece->strptime($timestring, "%d-%b-%Y %H:%M");
    say join ",", @F, $tp->yy . "W" . $tp->week . "D" . $tp->day_of_week . $rest;
' -- input.csv

IIRC, on MSWin you need to switch single and double quotes.

See pop , perlre , join for more details.

I want to convert the data with name Column_date

The following Python solution is based on datetime — Basic date and time types documentation. Please scroll down to strftime() and strptime() Behavior section for meaning of %y , %V , %u , … directives:

^^> python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from datetime import datetime
>>>
>>> ColDateOld = '08-jun-2017 00:00'   ### extract from `CSV`
>>> ColDateNew = datetime.strptime(ColDateOld, '%d-%b-%Y %H:%M').strftime("%yW%VD%u")
>>> print( ColDateNew)                 ### populate the result
17W23D4
>>>
>>>

Read and follow CSV File Reading and Writing as well.

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