strptime python中的用法
时间: 2024-06-13 17:07:10 浏览: 14
strptime是Python datetime库中的函数,用于将一个日期字符串转换成datetime日期格式以便后续处理。其使用方法为:datetime.strptime(date_string, format),其中date_string是要转换成日期的字符串,format根据date_string不同而不同。
下面举个简单的例子:
```python
import datetime as dt
date_str1 = '2020-10-1'
date_str2 = '2020/09/24'
real_time1 = dt.datetime.strptime(date_str1,'%Y-%m-%d')
real_time2 = dt.datetime.strptime(date_str2,'%Y/%m/%d')
print(real_time1) # 输出:2020-10-01 00:00:00
print(real_time2) # 输出:2020-09-24 00:00:00
time_delta = real_time1 - real_time2
print(time_delta) # 输出:7 days, 0:00:00
print(time_delta.days) # 输出:7
```
上述代码首先导入了datetime模块并重命名为dt,然后定义了两个日期字符串date_str1和date_str2。接着通过strptime函数将这两个日期字符串转换成datetime日期格式,并分别赋值给变量real_time1和real_time2。最后计算出了这两个日期之间的时间差,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)