0

I'm using bash and I would like to convert list of dates in format "08-Sep-2020 07:08:49" to timestamp. I found the way to do it one by one, line by line in a loop but I would like to convert whole file without using loops if possible. I was thinking about one line code like "cat /tmp/file | <some_command>"

Example file content:

08-Sep-2020 03:07:04
08-Sep-2020 02:20:46
08-Sep-2020 23:25:52

Currently I'm using

date -d "09-Sep-2020 06:52:44" +%s

I would like to get another file or the same file with:

1599530824
1599528046
1599603952
dzafer
  • 23
  • 4
  • 1
    Does this answer your question [Converting a file of dates into unix time with awk](https://stackoverflow.com/questions/25539996/converting-a-file-of-dates-into-unix-time-with-awk)? – Rfroes87 Sep 09 '20 at 16:57
  • 5
    Or this: `xargs -n1 date +%s -d outfile` – Léa Gris Sep 09 '20 at 16:59
  • Great, thanks for help.It works. Command is adding "1599519600" between the lines but this is not a problem, I can cut this line with sed -n '/1599519600/!p' – dzafer Sep 09 '20 at 17:22
  • 1
    It's unusual to have a file that;s just a bunch of dates and just want a bunch of seconds output so if that's not **all** your input file contains then [edit] your question to provide more truly representative sample input/output so we can help you. – Ed Morton Sep 09 '20 at 17:23
  • @EdMorton My file contains list of tasks and time in different time zones. By converting time to timestamp I have now possibilities to sort them and calculate in easy way and use easy "if" conditions to compare two tasks. It is much easier way than converting time zones. – dzafer Sep 09 '20 at 17:42
  • 1
    There's nothing in the answers posted so far that take TZ into account when converting to timestamps so YMMV. The comparison you describe would be more usefully done in an awk script that maps timestamps than outside of it in a calling shell script. You might want to ask a followup question with a bigger scope encompassing what you're trying to do with these timestamps and what your input/output really looks like. – Ed Morton Sep 09 '20 at 17:54

2 Answers2

2

Use GNU Date

If you have the GNU (not BSD) date command, you can use xargs to iterate over your dates. For example:

$ xargs -I{} -L1 date -d "{}" "+%s" < timestamps 
1599548824
1599546046
1599621952

Use Ruby DateTime

Another option is to use Ruby's DateTime module to do the conversion as a shell one-liner. For example:

$ ruby -r date -ne 'puts DateTime.parse($_).strftime "%s"' timestamps 
1599534424
1599531646
1599607552
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
1

With GNU awk for mktime():

$ awk -F'[ :-]' '{print mktime($3" "((index("JanFebMarAprMayJunJulAugSepOctNovDec",$2)+2)/3)" "$1" "$4" "$5" "$6)}' file
1599552424
1599549646
1599625552
Ed Morton
  • 188,023
  • 17
  • 78
  • 185