I have a CSV file in the following format
YYYY-mm-dd HH:MM:SS Some commentary text
YYYY-mm-dd HH:MM:SS Some commentary text
YYYY-mm-dd HH:MM:SS Some commentary text
YYYY-mm-dd HH:MM:SS Some commentary text
etc.
How can I add 2 hours to each date entry? I know the date is going to be in the first 19 characters in each line.
快速而肮脏的解决方案:
while read line ; do OldDate="$(echo "$line"| awk '{print $1" "$2}')" ; NewDate=$(date "+%Y-%m-%d %H:%M:%S" -d "$OldDate +2 hours"); echo "$line" | sed "s/$OldDate/$NewDate/g" ; done < original.csv > modified.csv
awk -v "DecalHour=2" '
{
OldString = substr( $0, 20)
OldTime = substr( $0, 1, 19)
gsub( /[^[:digit:]]/, " ", OldTime)
NewTime = mktime( OldTime ) + DecalHour * 60 * 60
NewStringTime = strftime( "%Y-%m-%d %H:%M:%S", NewTime)
# old - new
#print $0 " -> " NewStringTime OldString
# only new content
print NewStringTime OldString
}
' YourFile
Comment:
You can do it in Python also
"""input
2017-01-01 12:00:00,Some commentary text
2017-01-02 12:00:00,Some commentary text
2017-01-03 12:00:00,Some commentary text
2017-01-04 12:00:00,Some commentary text
"""
#said it was a csv, right :-)
import numpy as np
import pandas as pd
df=pd.read_csv("data.csv",names=[0,1])
df[0]=pd.to_datetime(df[0])+np.timedelta64(2,'h')
df.to_csv("/tmp/ans.csv",index=False,header=False)
"""
output looks like this:
2017-01-01 14:00:00,Some commentary text
2017-01-02 14:00:00,Some commentary text
2017-01-03 14:00:00,Some commentary text
2017-01-04 14:00:00,Some commentary text
"""
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.