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


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


Python datetime.replace() 方法

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

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

模塊:

    import datetime

類:

    from datetime import datetime

用法:

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

參數:

  • year:實例的新年份值(範圍:1 <= 年份 <= 9999)
  • month:實例的新月份值(範圍:1 <= 月份 <= 12)
  • day:實例的新日期(範圍:1<= 天 <= 31)
  • hour:在範圍內(24)
  • minute:在範圍內(60)
  • second:在範圍內(60)
  • microsecond:在範圍內(1000000)
  • tzinfo:object 作為 tzinfo 參數傳遞給 datetime 構造函數,或者 None 如果沒有傳遞。
  • fold:[0,1]

返回值:

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

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

例:

## Python program explaining the 
## use of datetime class instance methods

from datetime import datetime
import pytz

## Creating an instance
x = datetime(2019, 9, 25,4,54,23)
print("Datetime entered was:", x)
print()

x = datetime.now()
print("Today's date and time:", x)

## Using replace() method 
d = x.replace(year = 2022)
print("New date after changing the year:", d)
print()

d = x.replace(month=1)
print("The date after changing the month:", d)
print()

d = x.replace(day=3)
print("The date after changing the day:", d)
print()

d = x.replace(year=2025, day=30)
print("The date after changing the day and year:", d)
print()

d = x.replace(year= 1999, month =12, day=3)
print("The date after changing the year, month and day:", d)
print()

d = x.replace(hour = 12)
print("The date after changing the hour:",d)
print()

d = x.replace(minute= 4)
print("The date after changing the minute attribute:",d)
print()

d = x.replace(year=2220, month=10, day=28, hour=21, minute =5, second = 20)
print("The date after the changes:",d)
print()

timezone = pytz.timezone("Asia/Kolkata")
d = x.replace(tzinfo=timezone)
print("The date after changing the tzinfo:",d)

輸出

Datetime entered was:2019-09-25 04:54:23

Today's date and time:2020-04-30 19:11:10.683769
New date after changing the year:2022-04-30 19:11:10.683769

The date after changing the month:2020-01-30 19:11:10.683769

The date after changing the day:2020-04-03 19:11:10.683769
The date after changing the day and year:2025-04-30 19:11:
10.683769
The date after changing the year, month and day:1999-12-03
 19:11:10.683769

The date after changing the hour:2020-04-30 12:11:10.683769

The date after changing the minute attribute:2020-04-30 19
:04:10.683769

The date after the changes:2220-10-28 21:05:20.683769

The date after changing the tzinfo:2020-04-30 19:11:10.683
769+05:53


相關用法


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