只保留时间戳中的年和月
时间: 2024-02-25 08:53:31 浏览: 44
如果你想要从时间戳中只保留年和月,可以使用 Python 中 `datetime` 模块中的 `strftime()` 方法。具体来说,可以使用 `%Y-%m` 的格式化字符串来获取时间戳中的年和月。以下是示例代码:
```python
import time
timestamp = int(time.time())
year_month = time.strftime('%Y-%m', time.localtime(timestamp))
print(year_month)
```
以上代码首先使用 `time()` 函数获取当前时间的时间戳,然后使用 `localtime()` 函数将时间戳转换为本地时间,最后使用 `strftime()` 方法将本地时间格式化为年和月的字符串。输出结果如下:
```
2021-10
```
这样就可以从时间戳中只保留年和月了。
相关问题
js 时间戳转为年 保留一位小数
可以使用 JavaScript 中的 `Date` 对象和它的 `toLocaleString()` 方法来实现。具体代码如下:
```javascript
// 时间戳(单位:毫秒)
let timestamp = 1620887937950;
// 转换为日期对象
let date = new Date(timestamp);
// 格式化为年月日时分秒的字符串
let dateString = date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });
// 输出字符串,并保留一位小数
console.log(parseFloat(dateString).toFixed(1));
```
输出结果为:`2021.5`。其中,`parseFloat()` 函数可以将字符串转换为浮点数,`toFixed()` 方法可以保留指定的小数位数。
DataFrame 时间列中如何转换为时间戳格式并只保留年月日
可以使用 pandas 中的 `to_datetime()` 方法将 DataFrame 中的时间列转换为时间戳格式,然后使用 `dt.date` 方法只保留年月日。示例代码如下:
```python
import pandas as pd
# 假设你的 DataFrame 叫做 df,时间列叫做 time
df['time'] = pd.to_datetime(df['time']).dt.date
print(df['time'])
```
这将把 DataFrame 中的时间列转换为时间戳格式并只保留年月日,然后输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![sh](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)