2

私のpythonベースのアプリケーションでは、ユーザーは日付区切り記号のバリエーションを使用してdd / mm / yyの形式で日付を入力できます(区切り記号として/、-またはスペースを使用できるように)。したがって、これらはすべて有効な日付です。

10/02/2009
07 22 2009
09-08-2008
9-9/2008
11/4 2010
 03/07-2009
09-01 2010

テストするために、そのような日付のリストを作成する必要がありますが、これらの日付文字列とセパレーターのランダムな組み合わせを自動生成する方法がわかりません。

これは私がやり始めたことです:

date = ['10', '10', '2010']
seperators = ['/', '-', ' ']
for s in seperators:
    new_date = s.join(date)
4

3 に答える 3

2

I think the previous answers didn't really help too much. If you choose "day" as a number from 1-31 and "month" as any number from 1-12 in your test data, your productive code MUST raise Exceptions somewhere - 02/31/2013 should not be accepted!

Therefore, you should create random, but valid dates and then create strings from them with arbitrarily chosen format strings. This is what my code does:

import datetime
import time
import random

separators = ["/",",","-"," "]
prefixes = [""," "]

def random_datetime(min_date, max_date):
    since_epoch_min = time.mktime(min_date.timetuple())
    since_epoch_max = time.mktime(max_date.timetuple())
    random_time = random.randint(since_epoch_min, since_epoch_max)
    return datetime.datetime.fromtimestamp(random_time)

def random_date_string_with_random_separators(dt):
    prefix = random.choice(prefixes)
    sep1 = random.choice(separators)
    sep2 = random.choice(separators)

    format_string = "{}%m{}%d{}%Y".format(prefix, sep1, sep2)
    return dt.strftime(format_string)



min_date = datetime.datetime(2012,01,01)
max_date = datetime.datetime(2013,01,01)

for i in range(10):
    print random_date_string_with_random_separators(
                    random_datetime(min_date, max_date)
          )

This should cover all cases (if you take more than ten values).

Nevertheless, I have two remarks:

Don't use random data as test-input

You'll never know if someday your test will fail, maybe you don't catch all possible problems with the data generated. In your case it should be o.k., but generally it's not good practice (if you have another choice). Alternatively, you could create a well-thought set of hard-coded input strings where you cover all corner cases. And if someday your tests fail, you know it's no random effect.

Use well-tested code

For the task you describe, there's a library for that! Use dateutil. They have a fantastic datetime-parser that swallows almost everything you throw at it. Example:

from dateutil import parser

for i in range(10):
    date_string = random_date_string_with_random_separators(
                    random_datetime(min_date, max_date)
          )
    parsed_datetime = parser.parse(date_string)
    print date_string, parsed_datetime.strftime("%m/%d/%Y")

Output:

 01 05,2012 01/05/2012
05 17-2012 05/17/2012
06-07-2012 06/07/2012
10 31,2012 10/31/2012
 10/04,2012 10/04/2012
 11 16,2012 11/16/2012
 03/23 2012 03/23/2012
02-26-2012 02/26/2012
 01,12-2012 01/12/2012
12-21 2012 12/21/2012

Then you can be sure it works. dateutilhas tons of unit tests and "just will work". And the best code you can write is code you don't have to test.

于 2013-09-04T11:12:01.803 に答える
0

これらの日付を自動的に作成してリストに追加するには、次のようにします。

from random import choice, randrange
dates = []
s = ' -/'
for i in range(100):
  dates.append( "%i%s%i%s%i" % (randrange(1,13), choice(s), randrange(1,32), choice(s), randrange(2000,2019) ) )
print dates
于 2013-09-04T10:20:16.273 に答える
0

入力で特定の情報を提供することをお勧めします。

例えば:

date = raw_input("Enter date (mm/dd/yyyy): ")

strptime()それが正しいかどうかを確認するために使用します。

try:
  date = time.strptime(date, '%m/%d/%Y')
except ValueError:
  print('Invalid date!')

参考文献:

http://docs.python.org/2/library/time.html#time.strptime

Python 3.x で日付を検証するにはどうすればよいですか?

于 2013-09-04T10:11:16.557 に答える