Python datetime replace пример

Python datetime.datetime.replace() Method

Python datetime.datetime.replace() Method

  1. Syntax
  2. Example 1: Modify Date, Time, and Timezone Details
  3. Example 2: Convert a Timezone-Aware datetime to a Naive Instance

Python is a dynamic and famed general-purpose language. It is enriched with various use cases and support libraries and has a ton of support from its developers.

It offers a datetime module, which is built-in, that makes working with date, time, and timezones a piece of cake. This module provides methods and classes such as date , datetime , tzinfo , timezone , and timedelta to work with date and time.

These classes are flooded with numerous functions and attributes and offer robust features.

A date, along with time, is known as DateTime . Creating datetime objects can sometimes be tedious because they accept many values such as hour , day , minutes , timezone , seconds , etc.

Instead of manually creating a new datetime object, we can use an existing object, tweak its values according to our needs and generate a new datetime object.

Every datetime object owns a replace() that allows us to specify new values for its attributes and generate a new datetime object with those values. In this article, we will dive deep into the replace() method and thoroughly understand it with the help of some relevant examples.

Syntax

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 ) 

Parameters

Returns

The replace() method returns a new datetime object with all the same attributes as the original object, except for those attributes for which new values were provided.

Note that if tzinfo is set to None , a timezone-unaware datetime object is returned for which no conversions are performed for date and time.

By default, for naive or timezone-unaware objects, date and time are stored according to UTC or Coordinated Universal Time.

Example 1: Modify Date, Time, and Timezone Details

import datetime  cet = datetime.timezone(datetime.timedelta(hours = 2), name = "CET") ist = datetime.timezone(datetime.timedelta(hours = 5, minutes = 30), name = "India") d = datetime.datetime(2022, 8, 25, 12, 33, 45, 234154) print("Naive DateTime:", d) d = d.astimezone(cet) print("Timezone-aware DateTime:", d) print("Changed Date:", d.replace(year = 2001, month = 5, day = 20)) print("Changed Time:", d.replace(hour = 10, minute = 11, second = 30, microsecond = 0)) print("Changed Timezone:", d.replace(tzinfo = ist)) 
Naive DateTime: 2022-08-25 12:33:45.234154 Timezone-aware DateTime: 2022-08-25 14:33:45.234154+02:00 Changed Date: 2001-05-20 14:33:45.234154+02:00 Changed Time: 2022-08-25 10:11:30+02:00 Changed Timezone: 2022-08-25 14:33:45.234154+05:30 

The Python code above first creates a datetime object. It also creates two timezone objects, the CET timezone ( +02:00 ) and the IST timezone ( +05:30 ).

Читайте также:  Openssl php extension have to be enabled

The naive datetime is then converted to a timezone-aware object using the astimezone() method. The timezone is set as CET, and the date and time values are adjusted accordingly.

Next, using the replace() method, the date, time, and timezone are updated. Note that when the timezone is updated to the IST timezone, the date and time values are not adjusted according to it, unlike the astimezone() method; they remain the same as before.

Example 2: Convert a Timezone-Aware datetime to a Naive Instance

import datetime  cet = datetime.timezone(datetime.timedelta(hours = 2), name = "CET") d = datetime.datetime(2022, 8, 25, 12, 33, 45, 234154) print("Naive DateTime:", d) d = d.astimezone(cet) print("Timezone-aware DateTime:", d) print("Changed Timezone:", d.replace(tzinfo = None)) 
Naive DateTime: 2022-08-25 12:33:45.234154 Timezone-aware DateTime: 2022-08-25 14:33:45.234154+02:00 Changed Timezone: 2022-08-25 14:33:45.234154 

The Python code above first creates a datetime object. This object is naive (it doesn’t know anything about the timezone; there is no ±HH:MM value).

Next, we create a new timezone-aware object using the astimezone() method of the object. This method accepts an object of a class subclassing the abstract datetime.tzinfo class and returns a new datetime object.

We set the timezone to CET or Central European Time. If we carefully observe the output, we will find that the time has changed by 2 hours; from 12:33:45.234154 to 14:33:45.234154+02:00 , and it has a timezone as well.

The CET timezone is 2 hours ahead of the UTC. Next, using the replace() method, we set the timezone to None .

Note that now the datetime object is once again naive, but the output tells a different story. The date and time values were not reverted to UTC-based values; the timezone changed ( 14:33:45.234154+02:00 to 14:33:45.234154 ).

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article — Python DateTime

Источник

Python datetime replace пример

Last updated: Feb 18, 2023
Reading time · 4 min

banner

# Add year(s) to a date in Python

Use the datetime.replace() method to add years to a date.

The replace method will return a new date with the same attributes, except for the year, which will be updated according to the provided value.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to a date my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2026-09-14 00:00:00 # ----------------------------------------------- # ✅ add years to the current date current_date = datetime.today() print(current_date) # 👉️ 2023-02-18 18:57:28.484966 result_2 = add_years(current_date, 2) print(result_2) # 👉️ 2025-02-18 18:57:28.484966

add years to date

The add_years function takes the date and the number of years we want to add and returns an updated date.

Читайте также:  Cpp to dll online

The datetime.replace method returns an object with the same attributes, except for the attributes which were provided by keyword arguments.

In the examples, we return a new date where the month and the day are the same but the year is updated.

The first example uses the datetime.strptime() method to get a datetime object that corresponds to the provided date string, parsed according to the specified format.

Once we have the datetime object, we can use the replace() method to replace the year.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to a date my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2026-09-14 00:00:00

The date string in the example is formatted as mm-dd-yyyy .

If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass for the second argument to the strptime() method.

Since we preserve the month and day of the month, we have to be aware that February has 29 days during a leap year, and it has 28 days in a non-leap year.

# The current date might be February 29th

The current date might be February 29th and adding X years returns a non-leap year where February 29th is not a valid date.

In this scenario, we update the year and set the day of the month to the 28th.

Copied!
def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28)

An alternative approach is to set the date to March 1st if February 29th doesn’t exist in that year.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist # set to March 1st) return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) # ✅ add years to a date my_str = '02-29-2024' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2024-02-29 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2027-03-01 00:00:00

the current date might be february 29

# Adding years to the current date

The second example adds years to the current date.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) current_date = datetime.today() print(current_date) # 👉️ 2023-07-22 20:24:47.538361 result_2 = add_years(current_date, 2) print(result_2) # 👉️ 2025-07-22 20:24:47.538361

The datetime.today() method returns the current local datetime .

Читайте также:  Https browser yandex ru help personalization extension html

# Only extract the date components

If you only need to extract the date after the operation, call the date() method on the datetime object.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist # set to March 1st) return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) now = datetime.now() print(now) # 👉️ 2023-02-18 18:59:48.402212 result = add_years(now, 1) print(result) # 👉️ 2024-02-18 18:59:48.402212 # 👇️ only get a date object print(result.date()) # 👉️ 2024-02-18

# Formatting the date

If you need to format the date in a certain way, use a formatted string literal.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) now = datetime.now() print(now) # 👉️ 2023-02-18 19:00:11.870596 result = add_years(now, 1) print(result) # 👉️ 2024-02-18 19:00:11.870596 # 👇️ format the date print(f'result:%Y-%m-%d %H:%M:%S>') # 👉️ 2024-02-18 19:00:11

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces — .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

# Add years to a date using the date() class

You can also use the date() class instead of the datetime class when adding years to a date.

Copied!
from datetime import date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) date_3 = date(2023, 9, 7) print(date_3) # 👉️ 2023-09-07 result_3 = add_years(date_3, 5) print(result_3) # 👉️ 2028-09-07

Here is an example that adds years to a date object that represents the current date.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to current date (using date instead of datetime) date_4 = date.today() print(date_4) # 👉️ 2022-06-20 result_4 = add_years(date_4, 6) print(result_4) # 👉️ 2028-06-20

The date.today method returns a date object that represents the current local date.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью