Linux 向CSV文件中的所有行添加2小时-CentOS
我有一个以下格式的CSV文件Linux 向CSV文件中的所有行添加2小时-CentOS,linux,date,csv,awk,sed,Linux,Date,Csv,Awk,Sed,我有一个以下格式的CSV文件 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 等等 如何为每个日期条目添加2小时?我知道日期将在每行的前19个字符中。快速肮脏解决方案: whil
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
等等
如何为每个日期条目添加2小时?我知道日期将在每行的前19个字符中。快速肮脏解决方案:
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
读行时;do OldDate=“$(echo“$line”| awk'{print$1”“$2}”;NewDate=$(日期“+%Y-%m-%d%H:%m:%S”-d“$OldDate+2小时”);回显“$line”| sed“s/$OldDate/$NewDate/g”;完成modified.csv
评论:
- 这可能是一行代码(性能更好),为了(自我)理解,代码使用中间变量进行传播
- 使用gawk,而不是posix awk(无时间功能)
- 时间格式固定为您的示例
- 使用时间(历元)加法(以秒为单位)允许一天过去(21:59:59之后)
"""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
"""
你已经试过什么了?这不是一个代码编写服务,但我们将帮助您改进一些您已经尝试过的东西。这是我正在编写的一个大脚本中缺少的一个小部分,该脚本旨在从Paradox数据库自动提取数据。我可以发布完整的脚本,但我看不出重点。我面临的唯一问题是,当我从悖论表中提取时,它会无缘无故地减去2小时。所以我想加上这两个小时。这是整个过程中唯一一个我不知道该怎么做的部分,即使我花了半天的时间研究了怎么做。@Mike3645,你应该解决问题的根源。问题很可能是由时区设置引起的。花一点时间编写一个小脚本,其中只包含您试图解决此特定问题的内容,这将使其他人更容易提供帮助。这对我来说很有效。运行起来需要一点时间,但是文件非常小,所以这个解决方案在我的例子中是有效的。
"""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
"""