python中的str到时间

发布于 2024-10-02 02:41:20 字数 154 浏览 4 评论 0原文

time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"

如何将上面的字符串转换为时间戳?

我需要减去上面的时间戳time2-time1

time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"

How to convert the above from string to time stamp?

I need to subtract the above timestamps time2-time1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

当梦初醒 2024-10-09 02:41:20

对于 Python 2.5+

from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) - 
        datetime.strptime(time1, format)
# 1 day, 0:00:00

编辑: 对于 Python 2.4

import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) - 
        time.mktime(time.strptime(time1, format))
# 86400.0

For Python 2.5+

from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) - 
        datetime.strptime(time1, format)
# 1 day, 0:00:00

Edit: for Python 2.4

import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) - 
        time.mktime(time.strptime(time1, format))
# 86400.0
月亮邮递员 2024-10-09 02:41:20
>>> t1 = datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
>>> t2 = datetime.strptime(time2, "%Y-%m-%d %H:%M:%S")
>>> t2-t1
datetime.timedelta(1)

>>> (t2-t1).days
1
>>> (t2-t1).seconds
0
>>> t1 = datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
>>> t2 = datetime.strptime(time2, "%Y-%m-%d %H:%M:%S")
>>> t2-t1
datetime.timedelta(1)

>>> (t2-t1).days
1
>>> (t2-t1).seconds
0
梦途 2024-10-09 02:41:20

如果你像我一样被困在 Python 2.4 系统上:

from time import strptime
from datetime import datetime

str_to_datetime = lambda st: datetime(*strptime(st, '%Y-%m-%d %H:%M:%S')[:6])

str_to_datetime('2010-04-20 10:07:30')

否则 datetime.strptime() 会工作得很好。

If you're stuck on Python 2.4 system like me:

from time import strptime
from datetime import datetime

str_to_datetime = lambda st: datetime(*strptime(st, '%Y-%m-%d %H:%M:%S')[:6])

str_to_datetime('2010-04-20 10:07:30')

Otherwise datetime.strptime() will work just fine.

錯遇了你 2024-10-09 02:41:20
import time

time1 = "2010-04-20 10:07:30"

time_tuple = time.strptime(time1, "%Y-%m-%d %H:%M:%S")

timestamp = time.mktime(time_tuple)
import time

time1 = "2010-04-20 10:07:30"

time_tuple = time.strptime(time1, "%Y-%m-%d %H:%M:%S")

timestamp = time.mktime(time_tuple)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文