开发者

Convert 12hr date/time string to 24hr datetime

Like other questions asked here, im looking to do a simple conversion of time formats. I've found answers on how to do this in Perl, but not in Python.

I have a string like so:

on Jun 03, 02010 at 10:22PM

and I'd like to convert it to a datetime object like this:

Thu, 03 Jun 2010 22:22:00 -0000

I have sliced up my input like so:

date = str(comment.div.contents[5].contents)
month = date[6:9]
day   = date[10:12]
year  = date[15:19]
time  = date[23:30]

which sets me up with some nice variables I can throw back into datetime but before I so, I must convert the time. Should I divide up time in the example above and calculate the hh and {AM开发者_StackOverflow|PM} separately?


Using dateutil:

import datetime as dt
import dateutil.parser as dparser

date_str='on Jun 03, 02010 at 10:22PM'
date=dparser.parse(date_str)
print(date)
# 2010-06-03 22:22:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Thu, 03 Jun 2010 22:22:00

If you can somehow strip out the pesky 'on' and change 02010 to 2010, in date_str then you could use dt.datetime.strptime:

date_str='Jun 03, 2010 at 22:22PM'
date=dt.datetime.strptime(date_str,'%b %d, %Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00

Or, as Muhammad Alkarouri points out, if date_strs always start with on and use a four-digit year prefixed by zero, then you could use

date_str='on Jun 03, 02010 at 22:22PM'
date=dt.datetime.strptime(date_str,'on %b %d, 0%Y at %H:%M%p')
print(date)
# 2010-06-03 22:22:00

Python's strftime and strptime use your machine's C functions of the same name. So check your local man page for what format codes are available for your machine. For a general list of format codes (which may be available) see http://au2.php.net/strftime.


You are probably better of using the standard library, namely time.strptime.

In particular, the time you mentioned can be converted to a time.struct_time like so

In [9]: time.strptime("on Jun 03, 02010 at 10:22PM", "on %b %d, 0%Y at %I:%M%p") 

Out[9]: time.struct_time(tm_year=2010, tm_mon=6, tm_mday=3, tm_hour=22, tm_min=22, tm_sec=0, tm_wday=3, tm_yday=154, tm_isdst=-1) #store in variable t

Now that we have the struct_time in t we can do

In [14]: time.strftime('%a, %d %b %H:%M:%S %z', t)

Out[14]: 'Thu, 03 Jun 22:22:00 '

Note that the zone information you required in "Thu, 03 Jun 22:22:00 -0000" (the -0000 bit) is not provided by the first format, therefore it won't appear in the result.


I'm pretty lazy, so I'd probably use strptime and strftime:

date = strptime(dateString, 'on %b %d, %Y at %I:%M%p')
date.strftime('%a, %d %b %H:%M:%S %z')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜