python小知识点【str+u,r,b|str<-->byte|strptime、strftime】

本文介绍了Python中关于字符串的str、u、r、b前缀的含义,特别是str与bytes之间的转换。同时,重点讨论了strptime和strftime函数在时间格式化中的应用,包括如何将字符串转换为时间格式,以及将时间转化为自定义格式的字符串。此外,还提供了一个实际案例,展示如何处理数据集中日期和时间字段的合并与类型转换。

1 str前加u r b

u'我爱中国!':后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。
r'hello\n\t\u':其后的转义字符转为普通字符串,去掉转义字符的反斜杠转义机制
b'201545':表示byte类型的数据

2 str<–>bytes ref

# bytes object  
 b = b"example"  
  
 # str object  
 s = "example"  
  
 # str to bytes  
 bytes(s, encoding = "utf8")  
  
 # bytes to str  
 str(b, encoding = "utf-8")  
  
 # an alternative method  
 # str to bytes  
 str.encode(s)  
  
 # bytes to str  
 bytes.decode(b)

3 strptime、strftime

datetime.strptime('2018-10-24','%Y-%m-%d').strftime('%Y%m%d')
strptime可以将字符串转为时间格式;strftime可以将时间转为任意格式的字符串形式

例子

# 现有时间序列数据通过pandas读取,为DataFrame类型;
# 其index是该数据的时间戳,df.index类型是:pandas.core.indexes.datetimes.DatetimeIndex
# 通过df.index.values可以获得值,类型是numpy.datatime64[ns]
# 可以通过.astype("datetime64[D]")将单位从ns转化成day
# 要想转换成datetime.time类型,通过.astype(datetime)
times = df.index.values.astype("datetime64[D]").astype(datetime)
# 下面是将datetime转换成所需要形式的str,通过.strftime
timestamps = []
for i in times:
    timestamps.append(datetime.strftime(i,'%Y%m%d'))
# 将'20080210'转为'2008-02-10'
# 可以通过字符串判断拼接转化,我喜欢用datetime,因为刚学会
datetime.strftime(datetime.strptime(holidays),'%Y%m%d'),'%Y-%m-%d')

python中各种时间库的用法,时间序列的一般处理方式

需求:数据集中日期和时间两个字段是分开的两列,现在需要将其合并成一列,并将字符串类型改成时间类型

df = pd.DataFrame({
    'Day': np.array(['2010-04-24', '2012-08-20', '2016-03-06', '2016-01-02', '2010-12-21'], dtype=np.datetime64), 
    'Hour': np.array([17, 10, 9, 10, 4], dtype=np.int64)})

>>> pd.to_datetime(df.Day) + pd.to_timedelta(df.Hour, unit='h')
0   2010-04-24 17:00:00
1   2012-08-20 10:00:00
2   2016-03-06 09:00:00
3   2016-01-02 10:00:00
4   2010-12-21 04:00:00
dtype: datetime64[ns]

代码参考

时间序列上、下采样resample
resample:T表示分钟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值