Convert string to time with python [duplicate]

筅森魡賤 提交于 2019-12-10 23:54:49

问题


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

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

2013-03-15, 7:43PM MDT

I have tried

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?


回答1:


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


来源:https://stackoverflow.com/questions/15447706/convert-string-to-time-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!