python - 字符串日期时间格式为 time() python 中的 unix 时间格式

标签 python datetime time

我知道这在其他地方一定是一个很好的问题,但我在 SO 上看到的大多数问题看起来都在朝着相反的方向发展。我了解如何将 FROM time.time() 转换为人类可读的日期时间格式,如下所示:

>>> import time, datetime
>>> thetime = time.time()
>>> thetime
1375289544.41976
>>> datetime.datetime.fromtimestamp(thetime).strftime("%Y-%m-%d %H:%M:%S")
'2013-07-31 12:51:08'

反方向的作用是什么?

>>> thetime = '2013-07-30 21:23:14.744643'
>>> time.strptime(thetime, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .744643

我想从字符串转到自纪元格式以来的秒数。

更新

这就是我正在使用的,但它看起来不够优雅——必须已经有一个函数可以做到这一点,对吧?

def datetostamp(x):
    thetime = x.split('.')
    return(time.mktime(time.strptime(thetime[0], "%Y-%m-%d %H:%M:%S")) + float('.'+thetime[1]))

>>> thetime = '2013-07-30 21:23:14.744643'
>>> datetostamp(thetime)
1375233794.744643

更新 2

也许更简单,我只是错过了几分之一秒的格式代码?

最佳答案

错过了几分之一秒的格式。

time.strptime(thetime, "%Y-%m-%d %H:%M:%S.%f")

关于python - 字符串日期时间格式为 time() python 中的 unix 时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17976447/

相关文章:

python - 显示每月 DataFrame 的前 5 个最大值

sql-server - 在sql server中存储日期时间(日期时间类型)时,它以什么格式存储?

python - 将字符串日期转换为时间戳并返回 python

javascript - 检查Javascript中的时差

android - 无法获取当前时间

python - 初始化可变大小的二维数组

python - 用 Python 控制圆包装

python - 表函数不在 shell 中打印

php - 数据库时间数据检索、基于时间的查询

time - Spanner 的只读事务