使用python将字符串转换为时间 [英] Convert string to time with python

查看:238
本文介绍了使用python将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几个stackoverflow文章,但仍然无法弄清楚这一点...

I have read a few stackoverflow posts but still can't figure this out...

我想抓取最近48小时内发布的craigslist帖子。发布时间是以下craigslist格式:

I want to crawl craigslist post posted within last 48 hours. Posted time is in the following format for craigslist:

2013-03-15,7:43 PM MDT

2013-03-15, 7:43PM MDT

我试过

string = "2013-03-15, 7:43PM MDT"

time.strptime(string, "%Y-%m-%d, %I:%M%p %Z")

但是明显的格式与字符串不匹配。这个时间字符串的格式应该是什么?

But apparent the format doesnt match the string. What should be the format for this time string?

推荐答案

问题是MDT。 Python的%Z不支持(至少对我来说似乎是这样)。可能有更好的解决方案,但这应该是有效的:

The problem is the MDT. Python's %Z doesn't support that (at least it seems so to me). There are probably better solutions, but this one should work:

import time
import datetime

#use the UTC which Python understands
a="2013-03-15, 7:43PM MDT".replace("MDT","UTC")
fs="%Y-%m-%d, %I:%M%p %Z"
c=time.strptime(a, fs)

#converting from UTC to MDT (time difference)
dt = datetime.datetime.fromtimestamp(time.mktime(c)) - datetime.timedelta(hours=6)
print dt

这篇关于使用python将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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