Convert timestamp (unix 13 digits) to datetime format of a complet column of a csv file using awk or sed

Viewed 378

I have a csv file multiple columns. The first columns has timestamps like,

1529500027127
1529500027227
1529500027327
1529500027428
1529500027528
1529500027628
1529500027728

I know you can do something like that for a specific timestamp:

date -d @1529500027528

But how can I select all values of the columns and do that? I tried the next command:

date -d "$(awk -F , -v OFS=, '$1/=1000')" file.csv

I am trying to understand how date command works with other commands.

2 Answers

Since sample of expected output is not given so could only test it with given 1st column values, written and tested in GNU awk. You could use strftime function of awk, also since OP hs mentioned Input_file is a csv file so mentioning FS and OFS as , here.

awk 'BEGIN{FS=OFS=","} {$1=strftime("%Y/%m/%d %H:%M:%S",$1/1000)}1' Input_file

From man awk for strftime:

strftime([format [, timestamp[, utc-flag]]]) Format timestamp according to the specification in format. If utc-flag is present and is non-zero or non-null, the result is in UTC, otherwise the result is in local time. The timestamp should be of the same form as returned by systime(). If timestamp is missing, the current time of day is used. If format is missing, a default format equivalent to the output of date(1) is used. The default format is available in PROCINFO["strftime"]. See the specification for the strftime() function in ISO C for the format conversions that are guaranteed to be available.

If you want to use an external date -d@.... command, you could do this:

awk -F, -v 'OFS=,' '{"date -d@"$1 | getline timestamp ; $1=timestamp; print}' filename

Obviously finding a builtin function to do the same job (in this case, the strftime function as suggested by another answer) is a more efficient solution in terms of execution time, but the above gives an example of how to call out to external programs that you may be already familiar with.

Related