lundi 19 mai 2014

python - conversion de chaîne en datetime - Stack Overflow


Short and simple. I've got a huge list of date-times like this as strings:


Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.


Any help (even if it's just a kick in the right direction) would be appreciated.


Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.




Check out strptime in the time module. It is the inverse of strftime.




from datetime import datetime

date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')

Link to the Python documentation for strptime


and a link for the strftime format mask




Use the third party dateutil library:


from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.




Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.


import time

def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy
tens = int(str(n)[-2:])
units = n % 10
if tens > 10 and tens < 20:
return suf[0] # teens with 'th'
elif units <= 3:
return suf[units]
else:
return suf[0] # 'th'

def day_suffix(t):
'''
Returns the suffix of the given struct_time day
'''
return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​



I have put together a project that can convert some really neat expressions. Check out timestring.


Here are some examples below:


pip install timestring
>>> import timestring
>>> timestring.Range('next week')
<timestring.Range From 03/03/14 00:00:00 to 03/10/14 00:00:00 4496004880>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>

Thank you




Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.


Python 3.2+:


>>> import time, datetime
>>> datetime.datetime.fromtimestamp(
... time.mktime(time.strptime("March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S")),
... tz=datetime.timezone(datetime.timedelta(hours=-3))
... ).isoformat()
'2014-03-05T20:13:50-03:00'

or alternatively


>>> datetime.datetime.strptime(
... "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))


Short and simple. I've got a huge list of date-times like this as strings:


Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.


Any help (even if it's just a kick in the right direction) would be appreciated.


Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.



Check out strptime in the time module. It is the inverse of strftime.



from datetime import datetime

date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')

Link to the Python documentation for strptime


and a link for the strftime format mask



Use the third party dateutil library:


from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.



Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.


import time

def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy
tens = int(str(n)[-2:])
units = n % 10
if tens > 10 and tens < 20:
return suf[0] # teens with 'th'
elif units <= 3:
return suf[units]
else:
return suf[0] # 'th'

def day_suffix(t):
'''
Returns the suffix of the given struct_time day
'''
return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))​​​​​​​


I have put together a project that can convert some really neat expressions. Check out timestring.


Here are some examples below:


pip install timestring
>>> import timestring
>>> timestring.Range('next week')
<timestring.Range From 03/03/14 00:00:00 to 03/10/14 00:00:00 4496004880>
>>> timestring.Date('monday, aug 15th 2015 at 8:40 pm')
<timestring.Date 2015-08-15 20:40:00 4491909392>

Thank you



Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.


Python 3.2+:


>>> import time, datetime
>>> datetime.datetime.fromtimestamp(
... time.mktime(time.strptime("March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S")),
... tz=datetime.timezone(datetime.timedelta(hours=-3))
... ).isoformat()
'2014-03-05T20:13:50-03:00'

or alternatively


>>> datetime.datetime.strptime(
... "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-3)))

0 commentaires:

Enregistrer un commentaire