问题
How can I convert the annoying 12h time format (with AM and PM) into the 24h time format?
I wanted to avoid external programs like awk
as in this example.
Since gnuplot has a time-specifier %p
for "am" and "pm" (check help time_specifiers
), I thought it would be easy. But the following code does not give the correct result, but a warning message:
warning: Bad time format in string
Maybe, I'm using %p
incorrectly?
Code:
### change 12h time format to 24h format (does not give correct results)
reset session
$Data12 <<EOD
12/31/19 8:12:01 AM
12/31/19 8:12:02 PM
12/31/19 12:00:03 am
12/31/19 12:00:04 pm
EOD
myTimeFmt12 = "%m/%d/%y %H:%M:%S %p"
myTimeFmt24 = "%d.%m.%Y %H:%M:%S"
set table $Data24
plot $Data12 u (strftime(myTimeFmt24,timecolumn(1,myTimeFmt12))) w table
unset table
print $Data24
### end of code
Result:
"tbTime12to24.plt" line 15: warning: Bad time format in string
"tbTime12to24.plt" line 15: warning: Bad time format in string
"tbTime12to24.plt" line 15: warning: Bad time format in string
"tbTime12to24.plt" line 15: warning: Bad time format in string
31.12.2019 08:12:01
31.12.2019 08:12:02
31.12.2019 12:00:03
31.12.2019 12:00:04
回答1:
That's a somewhat "lengthy" solution I have come up with by defining my own formula, although I was hoping for a short "gnuplot-integrated" solution.
Code:
### change 12h time format to 24h format
reset session
$Data12 <<EOD
12/31/19 8:12:01 AM
12/31/19 8:12:02 PM
12/31/19 12:00:03 am
12/31/19 12:00:04 pm
EOD
myTimeFmt12a = "%m/%d/%y"
myTimeFmt12b = "%H:%M:%S"
myTimeFmt24 = "%d.%m.%Y %H:%M:%S"
# change 12h am/pm format to 24h format
myTime12to24(t,p) = t+12*3600*(floor(t/3600)<12 && (p eq "PM" || p eq "pm") ? \
1 : floor(t/3600)==12 && (p eq "AM" || p eq "am") ? -1 : 0)
set table $Data24
plot $Data12 u (strftime(myTimeFmt24,timecolumn(1,myTimeFmt12a) + \
myTime12to24(timecolumn(2,myTimeFmt12b),strcol(3)))) w table
unset table
print $Data24
### end of code
Result:
31.12.2019 08:12:01
31.12.2019 20:12:02
31.12.2019 00:00:03
31.12.2019 12:00:04
来源:https://stackoverflow.com/questions/59552645/gnuplot-how-to-convert-12h-time-format-into-24h-time-format