python - 将字符串时间戳转换为 Python 日期时间(原为 : how to properly convert char into float or double in Python)

标签 python datetime unix-timestamp

这里我有这样的字符串"1322485986.672901000",数据类型是代表unixtime的字符串。我想在 Python 中将其转换为日期时间。

我使用的方式是 date = datetime.fromtimestamp(float(row[0])) row[0] 表示这样的值 1322485986.672901000,因为我有几个行。转换结果错误,它只计算点之前的数字。所以转换后的日期就像 2011-11-28 13:53:23.6729

我认为问题是float(row[0]),但我不知道如何解决这个问题,或者有谁知道如何以更好的方式将 unixtime 转换为 datetime?

非常感谢!

现在我得到的结果是 2011-11-28 14:13:06.672901

但是当使用在线转换器时,结果是 2011-11-28 13:13:06

最佳答案

您当前结果的一小时差异可能是时区应用的结果。

如果需要,您可以提供明确的时区——tzinfo objects 上的文档可以引导您直接创建时区对象,一旦创建,您只需传入参数:

from datetime import datetime, tzinfo, timedelta

timestamp = "1322485986.672901000"

class UTC(tzinfo):
    def utcoffset(self, dt):
         return timedelta(0)
    def tzname(self, dt):
        return "UTC"
    def dst(self, dt):
        return timedelta(0)


d1 = datetime.fromtimestamp(float(timestamp), UTC())
print d1

此代码为我打印 2011-11-28 13:13:06.672901+00:00。

关于python - 将字符串时间戳转换为 Python 日期时间(原为 : how to properly convert char into float or double in Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8315384/

相关文章:

python - 设置导航工具栏和拾取事件的顶级轴

python - Jupyter:安装新模块

php - .ics 日历文件 - 解析日期时间 - 时间格式是什么?

php - 将 unix 时间戳转换为 twitter/facebook 样式

python - 如何在 Python 中将纪元时间戳舍入到最接近的分钟?

php - 如何在 twig 中显示来自 Unix 时间戳的格式化日期?

Python倒计时小游戏需要指导

python - 在 ModelChoiceField Django 中使用 __unicode__ 以外的方法

java - 如何将 LocalDate 转换为 ChronoZonedDateTime?

ruby - 获取当前日历月开始对应的时间