python 13位时间戳转字符串 字符串里包含毫秒
时间: 2023-09-24 12:07:37 浏览: 84
可以使用Python标准库中的`datetime`模块来实现13位时间戳转换成字符串,并且包含毫秒。具体实现如下:
```python
import datetime
timestamp = 1616122263553 # 13位时间戳
dt = datetime.datetime.fromtimestamp(timestamp / 1000.0) # 转换成datetime对象
str_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f') # 格式化输出,包含毫秒
print(str_time) # 输出:2021-03-19 17:31:03.553000
```
在上面的代码中,我们首先将13位时间戳除以1000,得到的结果是秒数,然后使用`datetime.datetime.fromtimestamp()`方法将其转换成`datetime`对象。接着,使用`strftime()`方法将`datetime`对象格式化成指定的字符串格式,其中`%f`表示毫秒。
最后输出的字符串即为带毫秒的时间字符串。
相关问题
python 时间戳10位转日期显示毫秒
你可以使用Python内置的datetime模块来将10位时间戳转换为日期,并使用strftime()方法来指定日期的显示格式,包括毫秒。下面是一个示例代码:
```python
import datetime
timestamp = 1612345678 # 10位时间戳
# 将时间戳转换为datetime对象
dt = datetime.datetime.fromtimestamp(timestamp)
# 使用strftime()方法将日期格式化为带毫秒的字符串
formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted_date)
```
上述代码将输出类似于"2021-02-03 12:34:56.000000"的日期字符串,其中包含了毫秒部分。你可以根据需要调整strftime()方法中的格式字符串来满足你的需求。
python 毫秒级时间,时间戳转换
在 Python 中,可以使用 `datetime` 模块来进行时间和时间戳的转换。下面是一个例子:
```python
import datetime
# 获取当前时间的毫秒级时间戳
timestamp = datetime.datetime.now().timestamp() * 1000
print(timestamp)
# 将时间戳转换为 datetime 对象
dt = datetime.datetime.fromtimestamp(timestamp / 1000.0)
print(dt)
```
输出结果类似于:
```
1626915096720.184
2021-07-22 10:38:16.720184
```
其中,第一行代码获取当前时间的毫秒级时间戳,第二行代码将时间戳转换为 `datetime` 对象。如果需要将一个字符串类型的时间转换为 `datetime` 对象,也可以使用 `datetime.strptime` 方法,例如:
```python
time_str = '2021-07-22 10:38:16'
dt = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print(dt)
```
输出结果为:
```
2021-07-22 10:38:16
```
其中,第一个参数是待转换的字符串,第二个参数是字符串的格式化字符串,用于指定字符串中时间的格式。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)