python - 使用python将字符串转换为时间

标签 python datetime strftime strptime

我已经阅读了一些 stackoverflow 帖子,但仍然无法弄清楚......

我想抓取过去 48 小时内发布的 craigslist 帖子。 craigslist 的发布时间采用以下格式:

2013年3月15日下午7点43分(MDT)

我已经尝试过

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

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

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

最佳答案

问题出在 MDT 上。 Python 的 %Z 不支持这一点(至少对我来说是这样)。可能有更好的解决方案,但这个应该可行:

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 - 使用python将字符串转换为时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15447706/

相关文章:

python - 如何使用python通过移动一行在csv文件中创建新列

c# - 设置 Azure Webjob 时区

c++ - 时间不匹配

python - CLion:强制附加进程将进程附加到某个调试器

python - 为什么不同的变量名得到不同的结果(python2.7)?

datetime - 如何通过 flutter 中的设备位置获取 flutter 中的时区、语言和县 ID?

datetime - 为什么 map[time.Time]string 有时不起作用?

Python strftime 时钟

python - 我收到 ValueError : strftime format ends with raw % for root. Clipboard_append(d.strftime ("%I:%M %p"+% +"%"))

python - 将组合结果分组到带有子列表的列表中