Discuss / Python / 打卡

打卡

Topic source

野子Vito

#1 Created at ... [Delete] [Delete and Lock User]
import re
from datetime import datetime,timezone,timedelta

pattern=r'(((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9]))|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29))|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)))((\s+(0?[1-9]|1[012])(:[0-5]\d){0,2}(\s[AP]M))?$|(\s+([01]\d|2[0-3])(:[0-5]\d){0,2})?$))'
pattern_tz=r'UTC([\+\-][01]?[0-9]):00'

def to_timestamp(dt_str,tz_str):
    dtMatches = re.match(pattern,dt_str)
    tzMatches = re.match(pattern_tz,tz_str)

    if dtMatches==None:
        print('Please input valid time.')
        return -1
    if tzMatches==None:
        print('Please input valid timezone.')
        return -1

    tz = int(tzMatches.groups()[0])

    dt = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')

    dt = dt.replace(tzinfo=timezone(timedelta(hours=tz)))

    ts = dt.timestamp()

    return ts


if __name__=='__main__':
    t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
    assert t1 == 1433121030.0, t1

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

    print('Pass')

  • 1

Reply