【问题标题】:Convert string to datetime to epoch将字符串转换为日期时间到纪元
【发布时间】:2014-11-18 21:28:55
【问题描述】:

我正在使用 Python 查询一个 MySQL 表并获取一个字符串格式的日期时间,该日期时间存储在 row[3] 中。我需要将此字符串时间戳转换为纪元秒数。

import MySQLdb
import os
import datetime
try:
    db = MySQLdb.connect("localhost","root","","test" )
except MySQLdb.Error, e:
     print "Error %d: %s" % (e.args[0], e.args[1])
     sys.exit (1)

cursor = db.cursor()
cursor.execute ("SELECT * from main_tbl WHERE login_user_name='kumar'")
data = cursor.fetchall()

for row in data :
    print row[3]                                   ###printing 2014-09-26 12:24:23
    date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
    print date

执行时会抛出此错误:

2014-09-26 12:24:23
Traceback (most recent call last):
  File "test1.py", line 22, in <module>
    date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
TypeError: must be string, not datetime.datetime

我做错了什么?

我还尝试了以下方法:

epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));

但我得到这个错误:

Traceback (most recent call last):
  File "test1.py", line 29, in <module>
    epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
  File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "C:\Python27\lib\_strptime.py", line 322, in _strptime
    found = format_regex.match(data_string)
TypeError: expected string or buffer

【问题讨论】:

    标签: python python-2.7 datetime mysql-python epoch


    【解决方案1】:

    row[3] 中的值已经是 datetime.datetime 格式,因为它已被回溯清楚地指出。所以不需要创建变量date。您可以将 row[3] 直接用作 datetime.datetime 对象。

    试试打印吧:

    print type(row[3])
    

    应该将类型指定为 datetime.datetime

    【讨论】:

      【解决方案2】:
      row[3] is already in datetime.datetime format.
      

      从你的问题听起来你想转换为EPOCH 所以做类似的事情:

      import time
      epochTime = time.mktime(row[3].timetuple())
      print epochTime
      

      然后检查转换后的epoch是否正确:

      print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime))
      print row[3]
      

      验证最后两条语句是否有相同的输出。

      【讨论】:

        猜你喜欢
        • 2012-04-03
        • 2018-02-18
        • 2012-11-22
        • 2017-11-10
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        • 2023-03-18
        • 2019-08-21
        相关资源
        最近更新 更多