如何在Python中将`ctime`转换为`datetime`?

flr*_*eey 26 python datetime

import time
t = time.ctime()
Run Code Online (Sandbox Code Playgroud)

对我来说,t'Sat Apr 21 11:58:02 2012'.我有更多这样的数据.

我的问题是:

  • 如何转换tdatetimePython中?它有什么模块吗?

我试着赚一点时间dict然后转换t,但觉得这不是用Python做的最佳方式.

细节:

  • 我有一个ctime清单(如['Sat Apr 21 11:56:48 2012', 'Sat Apr 21 11:56:48 2012']).
  • 我想将内容转换为datetime,然后将其存储在dbwith中timestamp.

Cha*_*guy 32

您应该使用strptime:此函数根据格式解析表示时间的字符串.返回值是struct_time.

格式参数默认为%a %b %d %H:%M:%S %Y相匹配()由返回的ctime格式化.

因此,在您的情况下,只需尝试以下行,因为默认格式是来自ctime的格式:

import datetime
import time

datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
Run Code Online (Sandbox Code Playgroud)

返回: datetime.datetime(2012, 4, 21, 4, 22, 00)


小智 6

只需使用%c

datetime.datetime.strptime(time.ctime(), "%c")
Run Code Online (Sandbox Code Playgroud)