Discuss / Python / 作业10

作业10

Topic source

孤o赦免你

#1 Created at ... [Delete] [Delete and Lock User]

def to_timestamp(dt_str, tz_str):

    if not re.match(r'\d{2,4}[-/]\d{1,2}[-/]\d{1,2} \d{1,2}[:]\d{1,2}[:]\d{1,2}$', dt_str):

        raise ValueError('日期格式不标准')

    if not re.match(r'(UTC)*[\+\- ]*\d{1,2}:\d{2}', tz_str):

        raise ValueError('时区格式不标准')

    dt_p = re.split(r'[- :]+',dt_str)

    dt_l = list(map(int,dt_p))

    tz = re.match(r'([A-Za-z]*)([\+\- ]*)(\d+):(\d{2})',tz_str)

    fh = tz.groups()[1]

    hour = int(tz.groups()[2])

    minute = int(tz.groups()[3])

    if fh == "-":

        hour = -hour

        minute = -minute

    dt = datetime(*dt_l).replace(tzinfo=timezone(timedelta(hours=hour,minutes=minute)))  

    return datetime.timestamp(dt)

#测试 1433121030.0

ts1 = to_timestamp('2015-6-1 08:10:30', 'UTC7:00')

ts2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')

ts3 = to_timestamp('2015-6-1 5:40:30', '04:30')

print(ts1,ts2,ts3)


  • 1

Reply