Python Date – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 17:56:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python Date – Java2Blog https://java2blog.com 32 32 Get First Day of Next Month in Python https://java2blog.com/get-first-day-of-next-month-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-first-day-of-next-month-python https://java2blog.com/get-first-day-of-next-month-python/#respond Mon, 26 Dec 2022 06:19:34 +0000 https://java2blog.com/?p=21941 Get First Day of Next Month in Python

This tutorial will demonstrate how to get first day of next month in Python.

Using the datetime.replace() with datetime.timedelta() function

To get first day of next month in Python:

  • Use the datetime object to store the current date and time.
  • Use the datetime.replace() and datetime.timedelta() function to get first day of next month in Python.

See the code below.

import datetime
dt = datetime.datetime.now()
dt_new = (dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)
print(dt_new)

Output:

2023-01-01 02:59:52.077793

The datetime library is used to work with date and time values in Python. The datetime object can store such values and provide different methods to operate on them. The now() function returns the current date and time values.

The replace() function from this library can be used to replace values of different attributes from such objects. The timedelta object from this library can be used to represent different intervals of time.

In the code example above, we use these methods to get the first day of next month by adding one month to the datetime value and replacing the value of the day attribute with one.

Using the calendar.monthrange() function

To get first day of next month in Python:

  • Use the datetime object to store the current date and time.
  • Use the monthrange() function to get the days of month.
  • Use the replace() and timedelta() functions to get first day of next month in Python.

See the code below.

import datetime
from calendar import monthrange
days_month = lambda dt: monthrange(dt.year, dt.month)[1]
dt = datetime.datetime.now()
dt_new = dt.replace(day=1) + datetime.timedelta(days_month(dt))
print(dt_new)

Output:

2023-01-01 03:52:36.547092

The calendar library also provides an additional set of tools to work with datetime objects.

The monthrange() function is used to calculate the first day of month and the days of the month. In the above example, we use the days of the month value and add it to the current date. Then we replace the value of the day attribute with one.

Using the dateutil.relativedelta object

To get first day of next month in Python:

  • Use the datetime object to store the current date and time.
  • Use the datetime.relativedelta object to get first day of next month in Python.

See the code below.

import datetime
from dateutil import relativedelta
dt = datetime.datetime.now()
dt_new = dt + relativedelta.relativedelta(months=1, day=1)
print(dt_new)

Output:

2023-01-01 03:21:55.474191

The dateutil library provides an additional set of methods and objects to work with datetime objects. The relativedelta object is used to replace and add different intervals of time to datetime objects.

In the above example, we use the relativedelta object to get first day of next month in Python.

Conclusion

To conclude, we discussed several methods to get first day of next month in Python.

In the first method, we use the replace() function to replace the value of the day attribute and add a time interval using the timedelta object. In the next method, we follow the same logic as method one but we use the monthrange() function to obtain the value that needs to be added with the timedelta object.

In the final method, we discussed the dateutil library and the relativedelta object from this library to add and replace time values to get the first day of month in Python.

]]>
https://java2blog.com/get-first-day-of-next-month-python/feed/ 0
Get List of Months Between Two Dates in Python https://java2blog.com/get-list-of-months-between-two-dates-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-list-of-months-between-two-dates-python https://java2blog.com/get-list-of-months-between-two-dates-python/#respond Wed, 07 Dec 2022 18:04:45 +0000 https://java2blog.com/?p=21708 Use pandas.period_range() Method

To get the list of months between two specified dates in Python:

  • Use pandas’s period_range() to get list of months between start date and end date with freq='M'.
  • Use list comprehension to iterate over list of months.
  • For each month, use strftime() method to convert it in appropriate format.
import pandas as pd

start_date, end_date = "2021-10-10", "2022-02-08"

month_list = pd.period_range(start=start_date, end=end_date, freq='M')
month_list = [month.strftime("%b-%Y") for month in month_list]

print(f"Months that lie between '{start_date}' and '{end_date}' are: ")
print(*month_list, sep=", ")
print(f"Total months: {len(month_list)}")

The execution of the above program will print the following on the console.

Months that lie between '2021-10-10' and '2022-02-08' are: 
Oct-2021, Nov-2021, Dec-2021, Jan-2022, Feb-2022
Total months: 5

The pandas library is a powerful data analysis and manipulation tool for Python. It provides data structures and operations for manipulating numerical tables and time series.

It supports high-level data structures and functions for working with relational or labelled data. The pandas library provides the pd.period_range() method that creates a TimeSeries object from a date range and returns a tuple of the days between two dates.

It holds start, end, period, and freq as arguments. Of the three parameters: start, end, and period, exactly two must be specified; otherwise, the method will return a ValueError.

We used pd.period_range() to find the months between start_date and end_date by providing the Month end frequency M as an offset alias to the freq.

The strftime() function in Python formats date and time objects into strings according to the specified format. It is a part of the datetime module, which provides various functions for working with dates and times.

Once we got the month_list, we used list comprehension to apply the strftime() method to format every month of month_list using %b-%Y as format codes. There are many other format codes documented.

To print every month in month_list, we provided the print() method with sep=", " to the print statement to print the list separated by a comma.

Use Nested List Comprehension

To get the list of months between two dates in Python:

  • Use the datetime.strptime() method to convert start and end date to appropriate format.
  • Use the for loop to iterate year that lies in the range of start date’s year and end date’s year.
  • Use an inner for loop to iterate every month that lies in the below range().
  • In the range() function, set the start to start date's month if year equals start date's year; otherwise set it to 1.
  • In the range() function, set the end to (end date's month)+1 if year equals end date's year; otherwise set it to 13.
from datetime import datetime

dates = ["2021-10-10", "2022-02-08"]
start_date, end_date = [datetime.strptime(_, "%Y-%m-%d") for _ in dates]

month_list = [datetime.strptime('%2.2d-%2.2d' % (year, month), '%Y-%m').strftime('%b-%Y')
    for year in range(start_date.year, end_date.year+1)
    for month in range(start_date.month if year == start_date.year else 1,
                       end_date.month+1 if year == end_date.year else 13)]

print(f"Months that lie between '{dates[0]}' and '{dates[1]}' are: ")
print(*month_list, sep=", ")
print(f"Total months: {len(month_list)}")

On the successful execution of the above code, we will get the following output.

Months that lie between '2021-10-10' and '2022-02-08' are: 
Oct-2021, Nov-2021, Dec-2021, Jan-2022, Feb-2022
Total months: 5

The datetime module in Python provides classes for manipulating dates and times easily. From this module, we imported the datetime class.

The strptime() function of datetime parses a string and interprets it as a date and time in a specified format. We applied it on every date in dates to get formatted start_date and end_date.

We used the for loop to iterate every year lying in the range start_date.year and end_date.year. The loop creates a formatted month_list using strptime() and strftime() functions which we discussed earlier.

We used an inner for loop to iterate both dates concerning their months. In that loop, we used the range() function as:

  • We set the start to start_date.month if year equals start_date.year; otherwise, the program jumped the else part to set it to 1.
  • We set the end to start_date.month+1 if year equals end_date.year; otherwise, the program jumped the else part to set it to 13.

Printing is the same as we discussed while explaining the code snippet using the pandas.period_range() method.

]]>
https://java2blog.com/get-list-of-months-between-two-dates-python/feed/ 0
Check if Date is Greater than Today in Python https://java2blog.com/check-if-date-is-greater-than-today-python/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-date-is-greater-than-today-python https://java2blog.com/check-if-date-is-greater-than-today-python/#respond Mon, 28 Nov 2022 07:50:46 +0000 https://java2blog.com/?p=21417 Use Comparison Operator with now()

To check if the specified date is greater than today in Python:

  • Use .datetime.now() to get the current local time and date.
  • Create a datetime object using datetime.datetime() with the specified date and time.
  • Use the greater than(>) operator with if-else to assess if the given date is greater than today.
import datetime

today = datetime.datetime.now()
date = datetime.datetime(2023, 5, 13, 22, 50, 55) 

if date > today:
    print(True)
else:
    print(False)

The above code will show us the following output.

False

First, let’s understand what we mean by checking if a date is greater than today.

For instance, if we have a current date/time and some date/time from the future then the future’s date/time would be greater than the current date/time.

Similarly, the current date/time would be greater than the date/time of any day from the past.

Next, we imported the datetime module to work with date and time while checking if the specified date is greater than today or not but if your project requires date only then you are required to import the date class as from datetime import date.

After that, we used the datetime.datetime.now() function to have the current local time and date. Mostly, learners get confused to see datetime twice while using the now() function but it’s very simple.

Here, the first datetime is the module, the second datetime is the class and now() is a function of the datetime class which belongs to the datetime module.

Then, we instantiated the datetime class by specifying a future’s date/time. Lastly, we used the if-else statement which printed True if the given date/time is greater than today; otherwise False.

Now suppose, there might be a situation where we have to compare the given date/time with a different time zone’s current date/time. Let’s see how we can do that.

Compare the datetime of Different Time Zones

To examine if the date is greater than the different time zone’s today in Python:

  • Use .datetime.now() by specifying a different time zone, we are using Pacific Standard Time here.
  • Instantiate datetime by passing date and time.
  • Use localize() to make naive time zone aware.
  • Use the greater than(>) operator with if-else to compare two dates and print the results accordingly, True if the condition satisfies; otherwise False.
import datetime
import pytz
#Pacific Standard Time is used (UTC−08:00)
today = datetime.datetime.now(datetime
       .timezone(datetime
       .timedelta(hours=-8)))

date = datetime.datetime(2022, 11, 27, 22, 20, 55) 
date = pytz.utc.localize(date)

if date > today:
    print(True)
else:
    print(False)

The above code fence gives us the following output on successful execution.

False

The above code’s logic is similar to the one we implemented in the previous code block but we used the pytz library. Note that, you must have pytz installed on your machine.

The above program got the current date according to Pacific Standard Time. Here, datetime.timezone() implemented the tzinfo which was set to None in the previous example and that’s its default behaviour.

While datetime.timedelta() returned the duration which denotes the difference between two datetime, time or date objects to the microsecond resolution.

Next, we created a datetime object which contains the local date and time.

Remember that the datetime instance is naive by default so, we had to make both objects either aware datetime or naive datetime; otherwise, the code will generate TypeError saying can not compare offset-aware and offset-naive datetimes.

To avoid this error, we used the localize() method of the utc class which belongs to the pytz module. The utc.localize() is used to make a naive time zone aware.

Now the point is, how will we know which variable is naive or aware? An aware datetime has an associated time zone while naive doesn’t. So, the variable today is the aware datetime and date is the naive datetime.

Finally, we used if-else to compare both dates which resulted in True if date > today fulfils; otherwise, False.

Till this point, we were given date/time in numbers but assume that the project requires to get the date as string input in a specific format. For instance, we want to have dates as dd/mm/YYYY format.

Let’s learn how we can convert that string input to a datetime object and compare them.

Use Comparison Operator with strptime()

To look over if the date is greater than today in Python:

  • Use strptime() to specify a date as a string type value in the dd/mm/YYYY format.
  • Use the now() function to get the current local time and date.
  • Use the greater than(>) operator with if-else to compare where the date is greater than today or not and print True or False accordingly.
import datetime

date = datetime.datetime.strptime("25/10/2023", "%d/%m/%Y")
today = datetime.datetime.now()

if date > today:
    print(True)
else:
    print(False)

It will give us the following outcome.

True

In this code block, we used the strptime() method of the datetime class which belongs to the datetime module. It took two parameters; the first is the date in string format and the second is the format in which we want to represent the given date.

Further, the strptime() converts this specific format of string type date to a datetime object. After that, we get the current local date/time using .datetime.now().

Finally, the if-else statement is used to compare both results and display True/False based on the if condition. We’ll get True if the condition is satisfied; otherwise, False.

]]>
https://java2blog.com/check-if-date-is-greater-than-today-python/feed/ 0
Get Number of Business Days Between Two Dates in Python https://java2blog.com/get-number-of-business-days-between-two-dates-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-number-of-business-days-between-two-dates-python https://java2blog.com/get-number-of-business-days-between-two-dates-python/#respond Tue, 25 Oct 2022 18:45:19 +0000 https://java2blog.com/?p=20990 Python provides the datetime object to store and work with date and time values. These objects are compatible with various libraries and can be manipulated using different functions from such libraries.

One such operation is getting all the dates between a given range. This can be done in different ways as well using various functions.

Get Number of Business Days Between Two Dates in Python

This tutorial will show how to get number of business days between two dates in Python.

Using the weekday() Function

As mentioned, we can get all the dates between two given days in Python. For this, we use a timedelta object and a for loop. The timedelta object represents a specific period of time and we will use it to get the total number of days between two dates.

Then we will run a loop till this value and in every iteration add one day to the starting date and display it. To get number of business days between two dates in Python, we can add a single line of code in this method.

We will use the weekday() function which returns which day of the week a particular date is (0 for Monday and 6 for Sunday). If it is a weekday (less than 5 which is Saturday), we will increment a counter variable. We will display the value of this variable after the loop ends.

See the code below.

from datetime import date, timedelta
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
d = d2-d1
days = 0
for i in range(d.days+1):
    day = d1 + timedelta(days=i)
    if(day.weekday()<5):
        days = days + 1
print(days)

Output:

8

This method is very exhaustive and requires a lot of computation. We will find more direct methods below.

Using the numpy.busday_count() Function

This is probably the most direct and useful method to get number of business days between two dates in Python. The numpy library works well with datetime objects. The busday_count() function returns the total number of business days between two given dates in Python.

Note that this function does not include the ending date as one of the dates.

For example,

import numpy as np
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
days = np.busday_count(d1,d2)
print(days)

Output:

8

An additional advantage of this function is the use of the holidays parameter. We can specify the holidays using this parameter and those holidays are not counted as the business days.

See the code below.

import numpy as np
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
days = np.busday_count(d1,d2, holidays = ["2022-10-05"])
print(days)

Output:

7

In the above example, we specify the date 2022-10-05 as a holiday and therefore the count reduces by one.

Using the workdays Library

The workdays library was introduced to provide workday-like functions that are already present in excel. The networkdays() function from this library returns the total business days between two dates similarly to the previous function.

See the code below.

from workdays import networkdays
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
days = networkdays(d1,d2)
print(days)

Output:

8

This function also accepts a holidays parameter which works exactly like the one in the previous method.

Conclusion

To conclude this tutorial, we discussed several methods to get number of business days between two dates in Python. In the first method, we follow a very exhaustive approach of finding all the days between two dates and checking each date individually.

The second and third methods are very similar. We see the busday_count() and networkdays() functions can be used to get number of business days between two dates in Python and we can also specify the holidays that can be ignored as business days.

]]>
https://java2blog.com/get-number-of-business-days-between-two-dates-python/feed/ 0
Get All Dates Between Two Days in Python https://java2blog.com/get-all-dates-between-two-days-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-all-dates-between-two-days-python https://java2blog.com/get-all-dates-between-two-days-python/#respond Tue, 25 Oct 2022 10:15:57 +0000 https://java2blog.com/?p=20982 In Python, we can efficiently work with date and time values using the datetime library. This library provides datetime objects that can store such data. The dateutil, arrow libraries also allow us to process such values in Python.

Get All Dates Between Two Days in Python

In this tutorial, we will discuss how to get all dates between two days in Python. For this, we will take two datetime objects and return all the dates between these objects.

Using the datetime.timedelta Object

This method is very straight-forward. A timedelta object is used to store and represent different durations of time. We store the total number of days between two dates in such an object.

Then we will use a for loop and iterate till one more than the total days in this object. In the for loop, we will add a day (represented using a timedelta object) to the starting day and print it. Similarly, in the next iteration, the next day gets printed, and so on till the loop ends.

We implement this logic in the code below.

from datetime import date, timedelta
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
d = d2-d1
for i in range(d.days + 1):
    day = d1 + timedelta(days=i)
    print(day)

Output:

2022-10-05
2022-10-06
2022-10-07
2022-10-08
2022-10-09
2022-10-10
2022-10-11
2022-10-12
2022-10-13
2022-10-14
2022-10-15

Using the pandas.date_range() Function

The pandas module is used to work with DataFrame objects. Such objects frequently deal with date and time values and thus this module is equipped with functions that can operate on such values.

The date_range() function from pandas takes two dates and returns the total dates between these two dates including them both. We can use it to get all dates between two days in Python.

The object returned by this function can be iterated over using a for loop to display the dates individually.

See the code below.

import pandas as pd
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
d = pd.date_range(d1, d2)
for i in d:
    print(i)

Output:

2022-10-05 00:00:00
2022-10-06 00:00:00
2022-10-07 00:00:00
2022-10-08 00:00:00
2022-10-09 00:00:00
2022-10-10 00:00:00
2022-10-11 00:00:00
2022-10-12 00:00:00
2022-10-13 00:00:00
2022-10-14 00:00:00
2022-10-15 00:00:00

Using the dateutil Library

The dateutil library provides an extension of functionalities and objects that can work with datetime objects. The rrule module of this library implements the recurrence of RFC. With such an object, we can calculate the range between two dates.

To get all dates between two days in Python, we will need to use the DAILY frequency with the rrule() constructor. We will iterate over the same and display all the dates.

See the following example.

from dateutil.rrule import rrule, DAILY
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
for d in rrule(DAILY, dtstart=d1, until=d2):
    print(d)

Output:

2022-10-05 00:00:00
2022-10-06 00:00:00
2022-10-07 00:00:00
2022-10-08 00:00:00
2022-10-09 00:00:00
2022-10-10 00:00:00
2022-10-11 00:00:00
2022-10-12 00:00:00
2022-10-13 00:00:00
2022-10-14 00:00:00
2022-10-15 00:00:00

Using the numpy.arange() Function

In Python, we use the numpy library to create and work with array objects. The arange() function from this library is used to create an array containing all values between two ranges.

We will pass the start and end dates in the function. We will create a timedelta object of one day that will serve as the step parameter.

We can iterate over the array and display the dates individually.

import numpy as np
from datetime import date
d1 = date(2022, 10, 5) 
d2 = date(2022, 10, 15)
dt = timedelta(days = 1)
days = np.arange(d1, d2, dt).astype(datetime)
for d in days:
    print(d)

Output:

2022-10-05 00:00:00
2022-10-06 00:00:00
2022-10-07 00:00:00
2022-10-08 00:00:00
2022-10-09 00:00:00
2022-10-10 00:00:00
2022-10-11 00:00:00
2022-10-12 00:00:00
2022-10-13 00:00:00
2022-10-14 00:00:00

Conclusion

To conclude this article, we discussed several methods to get all dates between two days in Python. In the first method, we manually calculated the total days between two dates and use a timedelta object to add one day to the starting date till the ending date.

In the other three methods, we created the range between the two dates and displayed the dates individually. For this, we used pandas.date_range() function, the dateutil library and the numpy.arange() function respectively.

]]>
https://java2blog.com/get-all-dates-between-two-days-python/feed/ 0
Get First Day of Month in Python https://java2blog.com/get-first-day-of-month-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-first-day-of-month-python https://java2blog.com/get-first-day-of-month-python/#respond Tue, 25 Oct 2022 10:08:35 +0000 https://java2blog.com/?p=20976 The datetime objects defined in the datetime library provide a convenient way to store date and time values. Other libraries like dateutil also provide extended functionalities that can be used with such objects.

In this tutorial, we will discuss how to get first day of month in Python.

Get First Day of Month in Python

Essentially, we will work with a datetime object that has some specific date and we will try to get the date of the first day of the month from such objects.

Using the datetime.replace() Function

The replace() function from the datetime library can replace the specified values from a datetime object and return a new object with the replaced values. We can specify the new values with parameters like day, month, year, etc to replace the existing values.

To get first day of month in Python using this method, we will replace the day value of the object with one.

For example,

from datetime import datetime
print(datetime.today().replace(day=1))

Output:

2022-10-01 00:45:10.636726

In the above example, the today() function returns the current date and time . We replace the day value of this object with one by using the replace() function.

You can also format date to YYYYMMDD in Python.

Using the datetime.strftime() Function

The strftime() function returns the datetime object as a string in our desired format. We can specify the required format within the function.

To get first day of the month in Python, we will pass the 01-%m-%Y format which will return the first day of the month.

See the code below.

from datetime import datetime, timedelta
d1 = datetime.today()
print(d1.strftime("01-%m-%Y"))

Output:

2022-10-01

Using the datetime.timedelta Object

The timedelta object allows us to represent periods of time that can be added or subtracted to datetime objects. We can use such objects to get first day of month in Python.

In this method, we will create a timedelta object containing one day less than the current date. This object will be subtracted from the required datetime object. The result of this operation will be the datetime object with the first day of the month.

See the code below.

from datetime import datetime, timedelta
d1 = datetime.today()
d2 = d1 - timedelta(days = int(d1.strftime("%d"))-1)
print(d2)

Output:

2022-10-01 01:01:21.284710

In the above example, the strftime() function is used to return the day value of the datetime object. The int() function converts this day value to an integer. We return today’s date and subtract a timedelta object with one day less than the current date to return the first day of the month.

Using the arrow Library

The arrow library provides an alternative way to store and work with date and time values. The span attribute returns the first and last attributes over a specific time period.

We can use the month value with this attribute and extract the first element to get first day of month in Python.

For example,

import arrow
d =arrow.utcnow().span('month')[0]
print(d)

Output:

2022-10-01T00:00:00+00:00

Conclusion

In this article, we discussed several methods to get the first day of month in Python. The most used method involves the use of the replace() function where we replace the day value of a datetime object. The strftime() function works similarly but returns a string as the final output.

The third method involved the use of the timedelta object to subtract some days from the date. We also discussed an alternative library arrow to perform the same efficiently.

]]>
https://java2blog.com/get-first-day-of-month-python/feed/ 0
Remove Time from datetime in Python https://java2blog.com/remove-time-from-datetime-python/?utm_source=rss&utm_medium=rss&utm_campaign=remove-time-from-datetime-python https://java2blog.com/remove-time-from-datetime-python/#respond Fri, 21 Oct 2022 12:17:15 +0000 https://java2blog.com/?p=20237 1. Introduction

In Python programming, dealing with date and time is a common scenario. Often, there’s a need to manipulate datetime objects, such as extracting only the date part and discarding the time.

For instance, consider a datetime object representing 2023-11-24 15:30:00. The goal is to transform this into just the date 2023-11-24, removing the time component.

Let’s explore various methods for achieving this and understand the scenarios where each method is most appropriate.

2. Using the date() Method

This method is the most straightforward for getting only the date part.

The date() method is a built-in function of the datetime object, it extracts the date part (year, month, day) from a datetime object and returns it as a date object.

from datetime import datetime

dt = datetime.now()  # Assume dt is 2023-11-24 15:30:00
date_only = dt.date()  # date_only is now 2023-11-24

Please note that the returned date object is a separate type in Python, distinct from datetime, and it only contains date information.

When to use:
This is ideal to use when we need date object for further data manipulations and comparisons.

3. Using strftime() Method

strftime() stands for "String Format Time", it formats a datetime object into a string based on a specified format.

from datetime import datetime
dt = datetime.now()  # Assume dt is 2023-11-24 15:30:00
date_only = dt.strftime("%Y-%m-%d")  # date_only is the string "2023-11-24"

The format "%Y-%m-%d" tells strftime() to format the datetime object into a string containing only the year, month, and day. The output is a string, not a date or datetime object.

When to Use:
This is useful when we need the date in a string format, perhaps for display purposes or when the date needs to be part of a larger string.

4. Using replace() Method

The replace() method changes specified components of a datetime object to new provided values.

from datetime import datetime
dt = datetime.now()  # Assume dt is 2023-11-24 15:30:00
date_only = dt.replace(hour=0, minute=0, second=0, microsecond=0)  # date_only is now 2023-11-24 00:00:00

By setting hour, minute, second, and microsecond to zero, we effectively remove the time component. The type remains datetime, but the time is set to midnight (00:00:00).

Please note that this method does not change the original datetime object; instead, it creates a new one.

When to Use:

This method is useful when we need to keep the type as datetime for compatibility with other parts of our code or APIs that expect a datetime object.

5. Creating a New Date Object

This method involves creating a new date object using the year, month, and day from the datetime object.

from datetime import datetime
dt = datetime.now()  # Assume dt is 2023-11-24 15:30:00
date_only = datetime.date(dt.year, dt.month, dt.day)  # date_only is now 2023-11-24

Above code directly constructs a new date object. This is similar to using the date() method, but it’s more explicit.

When to Use:
This is useful when we want to be explicit about the creation of a new date object, or when constructing a date object based on parts of different datetime objects.

6. Using Pandas Library

Pandas, a popular data manipulation library in Python, offers functionality for handling datetime data, including extracting dates from datetime objects.

import pandas as pd
from datetime import datetime

# Creating a datetime object
dt = datetime.now()  # Assume dt is 2023-11-24 15:30:00

# Converting datetime to a Pandas Timestamp
timestamp = pd.to_datetime(dt)

# Extracting date from Pandas Timestamp
date_only = timestamp.date()  # date_only is now 2023-11-24
  • First, we convert the datetime object to a Pandas Timestamp using pd.to_datetime(). This is useful especially when dealing with series or dataframes in Pandas.
  • The date() method is then used on the Timestamp object to extract the date, similar to the standard datetime object’s date() method.
  • The output will be a datetime.date object containing only the year, month, and day.

When to Use:

This method is particularly useful when we’re already working within the Pandas ecosystem, such as when dealing with time series data in dataframes.

7. Conclusion

In Python, removing the time component from a datetime object can be done efficiently using several methods. The choice of method depends on the specific requirements of our task, such as whether we need the result as a string or a date object, and whether we need to maintain the datetime type. For most scenarios, the date() method is both simple and efficient. However, if the output format or type is a consideration, other methods like strftime() or replace() offer valuable alternatives.

]]>
https://java2blog.com/remove-time-from-datetime-python/feed/ 0
Check if Date Is Between Two Dates in Python https://java2blog.com/check-if-date-is-between-two-dates-python/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-date-is-between-two-dates-python https://java2blog.com/check-if-date-is-between-two-dates-python/#respond Mon, 26 Sep 2022 17:38:48 +0000 https://java2blog.com/?p=20794 Python allows us to store and work with date values very efficiently by providing the datetime module. This module has datetime objects that can store date and time values. There are other third-party packages as well that allows us to work with such values. We can also store dates as strings in Python.

In this tutorial, we will check if date is between two dates in Python.

Check if Date Is Between Two Dates in Python

There are multiple ways to check if date is between two dates in Python. Let’s go through them.

Using the datetime.Datetime Object to Check if Date Is Between Two Dates in Python

As discussed earlier, we can store date values in datetime objects. We can compare such objects using relational operators.

We can use them to check if date is between dates in Python. We can use them to compare whether a given date is less than and greater than the given ranges to see if it returns True or False.

See the code below.

import datetime
d1 = datetime.datetime(2022, 1,1)
d2 = datetime.datetime(2022,2,2)
d3 = datetime.datetime(2022,3,3)
print(d1

Output:

True
False

In the above example, we define three dates of d1, d2, and d3. We perform two comparisons. In the first one, we check whether d2 date lies between d1 and d3 and the comparison returns True. We then check whether d1 lies between d2 and d3 and we observe that False is returned since the condition is not True.

Using Tuples to Check if Date Is Between Two Dates in Python

This method does not involve the use of datetime objects and also we will not consider the year in a date. In this technique, we will use tuples to store the day and month of a date.

To check if date is between two dates in Python, we will similarly use relational operators as we did previously to compare different tuples that store the dates.

See the code below.

d1 = (1,31)
d2 = (2,22)
d3 = (3,13)
print(d1

Output:

True
False

Here, first element is tuple is month and second element is day.

In the above example, we create three dates with only their respective days and months in three tuples. The three tuples are compared to check if one tuple is between the other two tuples. The output is True where the date is between two dates and False when the date is not between the given dates.

Conclusion

This article demonstrated different ways to check if date is between two dates in Python.

We first discussed date values in Python and how they are stored in datetime objects. In the first method, we used such objects and compared them using relational operators to check if date is between two dates in Python.

In the second method, we similarly used tuples to check if date is between two dates in Python. The limitation of this method is that we are discarding the year of the date and only use the day and month value.

]]> https://java2blog.com/check-if-date-is-between-two-dates-python/feed/ 0 TypeError: Object of Type Datetime Is Not Json Serializable in Python https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/?utm_source=rss&utm_medium=rss&utm_campaign=typeerror-object-of-type-datetime-is-not-json-serializable-python https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/#respond Fri, 23 Sep 2022 08:13:12 +0000 https://java2blog.com/?p=20249 In Python, the datetime library allows us to create objects of the datetime class that can store and process date and time values efficiently. We can manipulate these objects according to our needs using the wide range of functionalities provided by this library.

JSON is a type of encoding for data that is used frequently to facilitate the exchange of data over networks. It stands for JavaScript Object Notation. Due to the heavy influence of objects like dictionaries and lists on this notation, the Python language works very efficiently with such data.

In Python, we have the json library that contains a wide range of functionalities to work with such type of data. JSON serialization means taking some data and converting it into a JSON string. In Python, this can be achieved using the json.dumps() function.

When we get the object of type datetime is not JSON serializable exception in Python, it means that the datetime object cannot be serialized into a JSON string. This is a TypeError which means that it is caused due to performing illegal function on the given type of data.

Let us see an example of this exception.

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c)
print(s)

Output:

TypeError: Object of type datetime is not JSON serializable

In the above example, we try to serialize a dictionary but the error is thrown because the dictionary contains a datetime object.

However, we can work around this and solve this exception using different ways.

💡 Quick fix

If you are looking for quick fix, you can just use default parameter with json.dumps() to fix the issue.

s = json.dumps(c, default = str);

Fix the object of type datetime is not JSON serializable exception in Python

The following section will discuss the different methods to fix the object of type datetime is not JSON serializable exception in Python.

Using the default parameter in the json.dumps() function

As discussed, the json.dumps() function is used to serialize some data to a JSON string. This function accepts a default parameter.

This parameter accepts a function that is applied to the object in case any TypeError exception is thrown. By using default parameter, the datetime object can be converted to a string by specifying the value of the parameter as the str function.

See the following example.

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, default = str)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

In the above example, we can see that the exception is avoided due to the presence of the default parameter and the datetime object gets converted to a string.

Another function, we can use is the datetime.isoformat() method. This method returns a provided datetime object as a string in the ISO format. We can use this method instead of the str function.

See the following example.

import json
from datetime import datetime
def fun(ob):
    if isinstance(ob, datetime):
            return ob.isoformat()
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, default = fun)
print(s)
{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

In the above example, we create a function fun that takes an object and if this object is of type datetime (checked using the isinstance() method) then it returns a string of this object in ISO format using the isoformat() method.

Using the cls parameter in the json.dumps() function

We can use the cls parameter in the json.dumps() function to serialize incompatible types. We will create a subclass of the json.JSONEncoder class that by default manages this. We will override the default method and convert the datetime object to a string using the str method.

For example,

import json
from datetime import datetime
class DatetimeEncoder(json.JSONEncoder):
    def default(self, ob):
        if isinstance(ob, datetime):
            return str(ob)
        return json.JSONEncoder.default(self, ob)
dt = datetime(2022,5,9,15,20,15)
c = {'Date':dt, 'Name': 'Jack'}
s = json.dumps(c, cls = DatetimeEncoder)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

The DatetimeEncoder class in the above example is a subclass of the json.JSONEncoder class. We define the default method to convert the datetime objects to strings.

Alternatively, we can also use the isoformat() method instead of the str function to get a string representation of the datetime object.

Using the str function

In the previous methods, we discussed how to get a string representation of the datetime object when encountered in the json.dumps() function. However, we can also just convert the object to a string directly before passing it for serialization using the str() function.

For example,

import json
from datetime import datetime
dt = datetime(2022,5,9,15,20,15)
c = {'Date':str(dt), 'Name': 'Jack'}
s = json.dumps(c)
print(s)

Output:

{“Date”: “2022-05-09 15:20:15”, “Name”: “Jack”}

Also, we can get the string representation using the isoformat() method.

Conclusion

To conclude, we discussed how to fix the object of type datetime is not JSON serializable exception in Python. We discussed several methods to tackle this error.

In the first method, we used specified the default parameter with the str and isoformat() functions to convert the datetime object to a string when encountered in the json.dumps() function.

Similarly, in the second method, we created a subclass of the json.JSONEncoder class that has a default method that handles datetime object in a similar way. We can also convert these objects beforehand as discussed in the final method.

]]>
https://java2blog.com/typeerror-object-of-type-datetime-is-not-json-serializable-python/feed/ 0