當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python time replace()用法及代碼示例

Python time.replace() 方法

time.replace() 方法用於操作模塊 datetime 的時間類對象。

它用於用相同的值替換時間,除了那些由括號中指定的關鍵字參數賦予新值的參數。它是一個實例方法,這意味著它適用於類的實例。

模塊:

    import datetime

類:

    from datetime import time

用法:

    replace(
        hour=self.hour, 
        minute=self.minute, 
        second=self.second, 
        microsecond=self.microsecond, 
        tzinfo=self.tzinfo, 
        * fold=0
        )

參數:

  • hour:在範圍內(24)
  • minute:在範圍內(60)
  • second:在範圍內(60)
  • microsecond:在範圍內(1000000)
  • tzinfo:object 作為 tzinfo 參數傳遞給 datetime 構造函數,或者 None 如果沒有傳遞
  • fold:[0,1]

如果值不在給定範圍內,則會引發 ValueError。

返回值:

該方法的返回類型是替換參數後的時間類對象。

例:

## Python program explaining the 
## use of replace() method

from datetime import time

## Creating an instance
x = time(4,54,23, 37777)
print("Time entered was:", x)
print()

## Using replace() method 
d = x.replace(hour = 22)
print("New time after changing the hour:", d)
print()

d = x.replace(minute=10)
print("New time after changing the minute:", d)
print()

d = x.replace(second=30)
print("Time after changing the second:", d)
print()

d = x.replace(hour=20, minute=30)
print("Time after changing hour and minute:", d)
print()

d = x.replace(hour= 19, minute =12, second=34, microsecond=3333)
print("Time after changes:", d)
print()

輸出

Time entered was:04:54:23.037777

New time after changing the hour:22:54:23.037777

New time after changing the minute:04:10:23.037777

Time after changing the second:04:54:30.037777

Time after changing hour and minute:20:30:23.037777

Time after changes:19:12:34.003333


相關用法


注:本文由純淨天空篩選整理自 Python time replace() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。