views:

202

answers:

4
datetime =  '0000-00-00 00:00:00'.split('-')

Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?

+5  A: 

One idea would be something like this (untested):

years, months, days = the_string.split('-')
days, time = days.split(' ')
time = time.split(':')

Or this, which fits your data better.

date, time = the_string.split(' ')
years, months, days = date.split('-')
hours, minute, seconds = time.split(":")
Deniz Dogan
+13  A: 

I'm guessing you also want to split on the space in the middle:

import re
values = re.split(r'[- :]', "1122-33-44 55:66:77")
print values
# Prints ['1122', '33', '44', '55', '66', '77']
RichieHindle
A: 

Using regexps, and using a pattern to match the desired format,

>>> pat = r"(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)"
>>> m = re.match(pat,'0000-00-00 00:00:00')
>>> m.groups()
('0000', '00', '00', '00', '00', '00')
>>>

A more verbose option, named groups, will pair field names with values (for @skurpur).

>>> pat = "(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d) (?P<hour>\d\d):(?P<min>\d\d):(?P<sec>\d\d)"
>>> m = re.match(pat,'0000-00-00 00:00:00')
>>> m.groupdict()
{'hour': '00', 'min': '00', 'month': '00', 'sec': '00', 'year': '0000', 'day': '00'}
>>>
gimel
...changing "p" to "pat". :) Also, "\d{4}" would be nicer IMO, and then using r"" instead of a normal string to be on the safe side.
Deniz Dogan
thank you, reformatted. How about (?P<year>\d{4}) groups?
gimel
Surely that would be much nicer, yes! Slightly less readable, but meh! :)
Deniz Dogan
+2  A: 

Maybe what you really want is to parse the date

>>> from time import strptime
>>> strptime( '2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S') 
time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
>>>
fabrizioM
This is right except that the date is obviously invalid (I hate mysql).
Dustin
@Dustin: so why not use `if` or `try` to filter out the NULL non-date?
John Machin