终于开始学习时间类操作了,之前应用需要时,学习过一遍,但听完就忘了,希望这次通过操作让自己记忆更深刻。
一、构造时间使用datetime库中的datetime类:
二、读取时间1) 读取“年份”
【脚本】
print(student['birthday'].dt.year)
【结果】
0 2000
1 2002
2 2001
3 2002
4 2007
5 2003
6 2001
Name: birthday, dtype: int64
【说明】
1) 使用datetime的dt属性的year属性。同理,dt还month\day\hour\minute\second的属性。
2) 使用datetime.now().year - student['birthday'].dt.year,可以实时计算年龄。
注意两点,一是这里now()后,没有加.dt;一是,这里datetime.now().year是一个int数据类型,可以直接减一个series的数据类型,就像student['age']+1 一样3) 在dt.year属性后,如果需要加上汉字“年”,可不像加数字一样,可以直接加,而是要应用一下str()函数,将时间将换我字符,再加一个字符/字符串,再加“年”,写成:
student['birthday'][0:1].dt.year.apply(str) + '年'而不能写成:
str(student['birthday'][0:1].dt.year) + '年'
三、转换时间 1) 将形如“2014-01-03”形式的文本字符串转成datetime类型数据,怎么做呢?
print(pd.to_datetime('2014-01-03'))
print(pd.to_datetime('03-01-2014'))注意:to_datetime是pandas的函数,所以一定要加pd.
2) 将一个不规则的字符串转成datetime类型,形如“03-01-2014年“,怎么做呢?
print(datetime.strptime('03-01-2014年','%m-%d-%Y年'))注意:I、这里的第二个参数是解释第一个参数的,指定第一个参数中哪个是年、月、日。
II、%Y要大写。
III、strptime中的p 是parse解析的意思
3) 那么怎样将一个datetime格式的数据输出成自己想要的格式呢?使用strftime() 与上面的strptime()一字之差哦
print(datetime.strftime(datetime.now(), 'today is :%Y-%m-%d'))today is :2020-09-03
但是,如果想输出这样的格式“今天是:2020-09-04“,再用上面方法就会编码错误,怎么处理呢?设置一下时区(locale),选择时区类型为中国。
import locale
locale.setlocale(locale.LC_CTYPE,'chinese')
print(datetime.strftime(datetime.now(), '今天是:%Y-%m-%d'))
四、时间的加减如果知道今天的日期,能不能直接通过减1的方法推出昨天的时间呢?
如:print(datetime.now() - 1 )我们发现会报错:
TypeError: unsupported operand type(s) for -:'datetime.datetime' and 'int'
系统不支持将一个时间类型与一个整形类型相减
正确的方法是:
from datetime import timedelta
print(datetime.now() - timedelta(days =1))
[size=15.3333px]
[size=15.3333px]
五、总结本节学习了:
1、datetime库中datetime类、timedelta类;
2、pd.to_datetime()函数、datetime.strptime()函数和datetime.strftime()函数。
3、学习了时区的设置:locale.setlocale(locale.LC_CTYPE,'chinese')
4、最后学习了使用timedelta(days =数字)的方法.