2021年4月12日 星期一

Python時間轉換介紹

時間元組(struct_time) : 這是一個由九個數值組裝起來的時間類型。如下表所示

位置 參數 意義 範圍

0 tm_year 西元年 四位數

1 tm_mon 月份 1~12

2 tm_day 日期 1~31

3 tm_hour 小時 0~23

4 tm_min 分鐘 0~59

5 tm_sec 秒數 0~59

6 tm_wday 星期 0~6

7 tm_yday 今年第幾天 1~366

8 tm_isdst 夏令時間 0 or 1 or -1

夏令時間的解釋依照各國的規定不一定一樣,這裡只做數字的解釋

  • 0 : 不使用夏令時間
  • 1 : 使用夏令時間
  • -1 : 不確定
時間格式

  • %a - abbreviated weekday name

  • %A - full weekday name

  • %b - abbreviated month name

  • %B - full month name

  • %c - preferred date and time representation

  • %C - century number (the year divided by 100, range 00 to 99)

  • %d - day of the month (01 to 31)

  • %D - same as %m/%d/%y

  • %e - day of the month (1 to 31)

  • %g - like %G, but without the century

  • %G - 4-digit year corresponding to the ISO week number (see %V).

  • %h - same as %b

  • %H - hour, using a 24-hour clock (00 to 23)

  • %I - hour, using a 12-hour clock (01 to 12)

  • %j - day of the year (001 to 366)

  • %m - month (01 to 12)

  • %M - minute

  • %n - newline character

  • %p - either am or pm according to the given time value

  • %r - time in a.m. and p.m. notation

  • %R - time in 24 hour notation

  • %S - second

  • %t - tab character

  • %T - current time, equal to %H:%M:%S

  • %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1

  • %U - week number of the current year, starting with the first Sunday as the first day of the first week

  • %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week

  • %W - week number of the current year, starting with the first Monday as the first day of the first week

  • %w - day of the week as a decimal, Sunday=0

  • %x - preferred date representation without the time

  • %X - preferred time representation without the date

  • %y - year without a century (range 00 to 99)

  • %Y - year including the century

  • %Z or %z - time zone or name or abbreviation

  • %% - a literal % character

時間格式(字串)改成時間戳

當資料室字串的時候,無法直接使用字串來做運算或比較,最快也做方便的方式就是直接轉成時間戳,讓大家都變成一個數值,再作分析。

Example

import time 
timeString = "2020-09-09 19:00:00" # 時間格式為字串
struct_time = time.strptime(timeString, "%Y-%m-%d %H:%M:%S") # 轉成時間元組
time_stamp = int(time.mktime(struct_time)) # 轉成時間戳
print(time_stamp)

output

1599678000

時間格式(字串)更改

時間格式的更改一定要透過時間元組的幫忙,先將原本的字串轉成時間元組,在將時間元組轉成新的字串。

Example

import time # 引入time

timeString = "2020-09-09 19:00:00" # 輸入原始字串
struct_time = time.strptime(timeString, "%Y-%m-%d %H:%M:%S") # 轉成時間元組
new_timeString = time.strftime("%Y %b %d %I:%M:%S %p", struct_time)
print(new_timeString)

output

'2020 Sep 09 07:00:00 PM'

取得現在時間

取得後可經由轉換成想要的字串,作為其他的用途。

Example

import time

nowTime = int(time.time()) # 取得現在時間
struct_time = time.localtime(nowTime) # 轉換成時間元組
timeString = time.strftime("%Y %m %d %I:%M:%S %P", struct_time) # 將時間元組轉換成想要的字串
print(timeString)

output

2020 09 09 12:05:24 pm

1.獲勝到天堂時間前一個天堂,後一個天堂(注意時間at s s的單邊,此一般時間re轉換為正式的時間戳時間,不注意重用%f毫秒)

def testfunc():
    today = date.today()
    print today,type(today)
    yesterday = date.today() + timedelta(days=-1)
    print yesterday,type(yesterday)
    yesterday = (date.today() + timedelta(days=-1)).strftime("%Y.%m.%d")
    print yesterday
    a = time.time()
    print a
    ltime = time.localtime(a)
    print "ltime",ltime
    gtime = time.gmtime(a)
    print gtime
    time_string = time.strftime('%Y.%m.%d.%H.%M.%S', ltime)
    gtime_string = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time()))
    print time_string
    print "gtime_string",gtime_string,type(gtime_string)

    date_str = "2018/11/13 17:32"
    print "start:", date_str
    timeArray = time.strptime(date_str, "%Y/%m/%d %H:%M")
    timeStamp = int(time.mktime(timeArray))
    timeStampPlusOneday = timeStamp + +86400
    # print timeStampPlusOneday
    timeArray = time.localtime(timeStampPlusOneday)
    otherStyleTime = time.strftime("%Y/%m/%d %H:%M", timeArray)
    print "other:", otherStyleTime

    print "test"
    yesterday = date.today() + timedelta(days=-1)
    yesterday = yesterday.strftime("%Y.%m.%d")
    print yesterday
    print yesterday + " 00:00:00"
    print "uesd:",time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time()))

2.在某個特定時間點內的判斷

def getNonWorkTime():
    # 范围时间
    a_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '2:00', '%Y-%m-%d%H:%M')
    b_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '5:00', '%Y-%m-%d%H:%M')
    c_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '7:00', '%Y-%m-%d%H:%M')
    d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '13:00', '%Y-%m-%d%H:%M')
    print a_time,b_time,c_time,d_time
    # 当前时间
    n_time = datetime.datetime.now()
    print "now:",n_time
    # 判断当前时间是否在范围时间内
    if b_time> n_time > a_time or d_time> n_time > c_time:
        print "not work"
    else:
        print "work"

3.預先存在時間為一分鐘,預先存在時間為一小時間

def oneMinStr():
    start = time.strftime('%Y/%m/%d %H:%M:%S', time.gmtime(time.time()))
    print "start:", start,type(start)
    timeArray = time.strptime(start, "%Y/%m/%d %H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    timeStampPlusOneday = timeStamp + -60
    # print timeStampPlusOneday
    timeArray = time.localtime(timeStampPlusOneday)
    endtime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
    print "other:", endtime,endtime.split()[1]
    s = "(" + endtime + "-" + start.split()[1] + ")"
    print s
def addOneHour():
    #date_str = "2018/11/13 17:32"
    date_str = "2019-02-21T16:00:00.000000Z"
    print "start:", date_str
    timeArray = time.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
    timeStamp = int(time.mktime(timeArray))
    timeStampPlusOneday = timeStamp + +3600
    # print timeStampPlusOneday
    #timeStamp = 1381419600
    dateArray = datetime.datetime.utcfromtimestamp(timeStampPlusOneday)
    otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
    print otherStyleTime  # 2013--10--10 15:40:00


    timeArray = time.localtime(timeStampPlusOneday)
    otherStyleTime = time.strftime("%Y/%m/%d %H:%M", timeArray)
    print "other:", otherStyleTime

    minTime = "2019-02-21T16:00:00.000000Z"
    maxTime = "2019-02-28T16:00:00.000000Z"
    gt = "2019-02-21T16:00:00.000000Z"
    lt = "2019-02-21T18:00:00.000000Z"

    print "initial time:", gt

    gtArray = time.strptime(gt, "%Y-%m-%dT%H:%M:%S.%fZ")
    #时间戳与字符类型互转
    timeStamp = int(time.mktime(gtArray))
    timeStampPlusOneHour = timeStamp + +3600
    print timeStampPlusOneHour
    timeArray = time.localtime(timeStampPlusOneHour)
    otherStyleTime = time.strftime("%Y-%m-%dT%H:%M:%SZ", timeArray)
    print "addOH", otherStyleTime


REF

沒有留言:

張貼留言