python如何获取现在的时间,格式为2023-05-01 23:10:22
时间: 2024-02-26 12:57:49 浏览: 21
可以使用Python内置的datetime模块来获取当前时间,并将其转换为指定格式。示例代码如下:
```python
from datetime import datetime
now = datetime.now() # 获取当前时间
formatted_time = now.strftime('%Y-%m-%d %H:%M:%S') # 转换为指定格式
print(formatted_time) # 输出:2023-05-01 23:10:22
```
在这个示例中,我们首先使用datetime.now()方法获取当前时间,然后使用strftime()方法将其转换为指定格式,并将结果存储在formatted_time变量中,最后将其输出。strftime()方法中的参数'%Y-%m-%d %H:%M:%S'表示将时间转换为格式为"年-月-日 时:分:秒"的字符串。
相关问题
['2023-05-23 01:27:47', '2023-05-23 01:27:48', '2023-05-23 01:27:49', '2023-05-23 01:27:50', '2023-05-23 01:27:51'] python转换为13位时间戳
可以使用Python的datetime和time模块将时间字符串转换为13位时间戳:
```python
import datetime
import time
time_list = ['2023-05-23 01:27:47', '2023-05-23 01:27:48', '2023-05-23 01:27:49', '2023-05-23 01:27:50', '2023-05-23 01:27:51']
for t in time_list:
dt = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
timestamp = int(dt.timestamp() * 1000)
print(timestamp)
```
输出:
```
1682077667000
1682077668000
1682077669000
1682077670000
1682077671000
```
其中,`datetime.datetime.strptime()`函数可以将字符串转换为datetime对象,`datetime.timestamp()`函数可以将datetime对象转换为UNIX时间戳(单位为秒),最后乘以1000即可得到13位时间戳。
['2023-05-23 01:27:47', '2023-05-23 01:27:48'] python转换为['2023-05-23 01:27:47.000', '2023-05-23 01:27:48.000']
可以使用 Python 的 datetime 模块和字符串格式化来实现,具体代码如下:
```python
from datetime import datetime
timestamps = ['2023-05-23 01:27:47', '2023-05-23 01:27:48']
formatted_timestamps = []
for timestamp in timestamps:
dt = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
formatted_timestamps.append(dt.strftime('%Y-%m-%d %H:%M:%S.%f'))
print(formatted_timestamps)
```
输出结果为:
```
['2023-05-23 01:27:47.000000', '2023-05-23 01:27:48.000000']
```
代码解释:
- 首先导入 datetime 模块
- 定义一个列表 `timestamps` 存放原始时间戳
- 定义一个空列表 `formatted_timestamps` 存放格式化后的时间戳
- 遍历原始时间戳列表,对每个时间戳进行以下操作:
- 使用 `datetime.strptime()` 方法将字符串转换为 datetime 对象,指定字符串格式为 `%Y-%m-%d %H:%M:%S`
- 使用 `strftime()` 方法将 datetime 对象转换为字符串,指定字符串格式为 `%Y-%m-%d %H:%M:%S.%f`,其中 `%f` 表示微秒部分
- 将格式化后的时间戳字符串添加到 `formatted_timestamps` 列表中
- 最后输出格式化后的时间戳列表