简体   繁体   English

带有字符串输出/格式的Python日期比较

[英]Python date comparison with string output/format

I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. 我目前正在尝试编写脚本以使工作中的功能自动化,但是我对Python并不十分熟悉。 I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not. 我正在尝试进行XML转储并比较特定条目的日期,以查看时间是否过去。

The date is in a particular format, given: 日期采用特定格式,给定:

<3-letter Month> <DD> <HH:MM:SS> <YYYY> <3-letter Timezone>

For example: 例如:

May 14 20:11:20 2014 GMT

I've parsed out a string in that raw form, and need to somehow compare it with the current time to find out if the time has passed or not. 我已经解析出了原始格式的字符串,并且需要以某种方式将其与当前时间进行比较,以了解时间是否过去了。 That said, I'm having a bit of trouble figuring out how I should go about either formatting my text, or choosing the right mask/time format in Python. 就是说,我在确定如何格式化文本或在Python中选择正确的掩码/时间格式方面遇到了一些麻烦。

I've been messing around with different variations of the same basic format: 我一直在搞弄相同基本格式的不同变体:

if(trimmed < time.strftime("%x") ):

Trimmed is the clean date/time string. 整理的是干净的日期/时间字符串。 Time is derived from import time . 时间是从导入时间得出的。

Is there a simple way to fix this or will I have to dig into converting the format etc.? 是否有解决此问题的简单方法,还是我必须深入研究转换格式等问题? I know the above attempt is simplistic, but I'm still very new to Python. 我知道上面的尝试很简单,但是我对Python还是很陌生。 Thanks for your time and patience! 感谢您的时间和耐心!

You should use combination of gmtime (for GMT time),mktime and datetime. 您应该结合使用gmtime(用于GMT时间),mktime和datetime。

from time import gmtime,mktime
from datetime import datetime

s = "May 14 20:11:20 2014 GMT"
f = "%b %d %H:%M:%S %Y GMT"
dt = datetime.strptime(s, f)
gmt = datetime.fromtimestamp(mktime(gmtime()))
if dt<gmt:
    print(dt)
else:
    print(gmt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM