如何在Python中将`ctime`转换为`datetime`? [英] How to convert `ctime` to `datetime` in Python?

查看:309
本文介绍了如何在Python中将`ctime`转换为`datetime`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import time
t = time.ctime()

目前对我来说, t 2012年4月21日星期六11:58:02 。我有更多这样的数据。

For me at the moment, t is 'Sat Apr 21 11:58:02 2012'. I have more data like this.

我的问题是:


  • 如何在Python中将 t 转换为 datetime ?有什么模块吗?

  • How to convert t to datetime in Python? Are there any modules to to it?

我试图将时间设置为 dict 然后转换 t ,但是感觉这不是用Python做到的最好方法。

I tried to make a time dict and then convert t, but feel like that’s not the best way to do it in Python.

详细信息:


  • 我有一个 ctime 列表(例如 ['Sat Apr 21 11:56:48 2012','Sat Apr 21 11:56:48 2012'] )。

  • 我想将内容转换为 datetime ,然后将其存储在 db 带有时间戳

  • I have a ctime list (like ['Sat Apr 21 11:56:48 2012', 'Sat Apr 21 11:56:48 2012']).
  • I want to convert the contents to datetime, then store that in a db with timestamp.

推荐答案

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

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

The format parameter defaults to %a %b %d %H:%M:%S %Y which matches the formatting returned by ctime().

因此,在您的情况下,请尝试以下行,因为默认格式是ctime中的格式:

So in your case just try the following line, since the default format is the one from ctime:

import datetime
import time

datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")

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

这篇关于如何在Python中将`ctime`转换为`datetime`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆