已知:csv文件中有一行为时间
目前时间的格式为2016-09-15 01:30:00
目标时间的格式为2016年9月15日-1:30(后面的秒可以去掉)
该任何转换啊?
使用pandas和strftime进行转换即可,参考代码:
import pandas as pd
import locale
locale.setlocale(locale.LC_CTYPE, 'chinese')#设置本地时域
df = pd.DataFrame({'date': ['2016-09-15 01:30:00', '2016-09-15 02:30:00']})#构建一个用于测试时间格式的简单数据框
d=pd.to_datetime(df.date).apply(lambda x:x.strftime('%Y年%m月%d日-%H:%M'))#用pandas中to_datetime将字符串先转换成日期格式,然后用apply函数逐个元素遍历操作,将时间格式转换。
print(d)
'''
0 2016年09月15日-01:30
1 2016年09月15日-02:30
Name: date, dtype: object
'''
用正则表达式替换
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
import re
s='2016-09-15 01:30:00'
s = re.sub(r'(\d{4})-0?(\d{1,2})-0?(\d{1,2}) 0?(\d{1,2}):0?(\d{1,2}):0?(\d{1,2})',r'\1年\2月\3日-\4:\5',s)
print(s)
from datetime import datetime
t = datetime.strptime('2016-09-15 01:30:00','%Y-%m-%d %H:%M:%S')
print(t.strftime('%Y年%m月%d日-%H:%M'))