Datetime убрать секунды python

Remove Seconds From Datetime in Python

This article focuses on how to remove seconds on Python datetime objects. The seconds can be removed in two ways – simply truncating seconds by turning them to 0 or by rounding off seconds into minutes.

In this post, we assume you want to work with datetime objects, string datetime formats, or pandas dataframes/series (the assumption is sufficient in most cases).

Remove Seconds from datetime: Using .replace()

The datetime object supports replacing arguments with values of our choice. The attributes provided by datetime.datetime and can be replaced include year, month, day, hour, minute, second, microsecond, and tzinfo (time zone information).

If we want to strip the second in datetime, we simply set the second argument to zero. Here are some examples.

In the above code, we were able to set seconds and/or microseconds to zero and, therefore, effectively remove it/them from the datetime object.

Читайте также:  Php обрезать строку троеточие

Suppose, instead of simply truncating, we round off the datetime value to the nearest minute – if seconds

time2 --> 2021-03-29 14:26:30 rounded time2 --> 2021-03-29 14:27:00 time2 --> 2022-08-11 16:32:20.940362 rounded time2 --> 2022-08-11 16:32:00 time3 --> 2022-06-12 08:07:38.005679 rounded time3 --> 2022-06-12 08:08:00 time4 --> 2022-11-28 12:12:21.005679 rounded time4 --> 2022-11-28 12:12:00

The function minute_round() sets seconds and microseconds to zero, retains hour as is, and timedelta rounds off seconds into the nearest minute.

Strip Seconds in datetime String

When dealing with datetime on string format, you must parse it before using replace to remove seconds. Parsing a string into datetime is achieved using .strptime(, ) function.

str_dt1_sec = datetime . strptime ( str_dt1 , «%Y-%m-%d %H:%M:%S» ) . replace ( second = 0 , microsecond = 0 )

The code snippet above does two things – change the string str_dt1 into a datetime object using strptime() and then, as before, use replace() to set seconds and microseconds to zero.

If you want to round off seconds, convert the string to datetime and proceed as before by calling the minute_round() function.

Sometimes strptime() function fails to parse some strings to datetime. If you find this limitation problematic based on your task, you can use the dateparser package instead (you might have to install the library before using it).

The package contains the parse() function, which can parse strings more efficiently than strptime(). Here are some examples.

Источник

Remove time from datetime in Python

The datetime library is a standard Python library that can be used to store and process date and time values. The library implements the datetime class that can store these values and manipulates them. We can use the constructor of this class to create such objects and initialize them with the required values.

It also has two classes called date and time that can store only the date and time values respectively.

Ways to remove time from datetime in Python

As discussed, the datetime object can store date and time values. In this tutorial, we will discuss how to remove time from datetime in Python to only display date values.

Using the date attributes to remove time from datetime in Python

The datetime constructor has different attributes to store the values. These are the day , month , year , hour , minutes , and seconds . We can access the required value using their respective attribute.

To remove time from datetime in Python, we can simply create a string by appending the values of only the date attributes from a given datetime object.

In the above example, we create a rem_time() function that takes a datetime object and returns the date values in a string. The date attributes are returned as an integer so we need to convert them to a string using the str() function.

Instead of a string, we can also get the final result in a date object. Objects of this class contain only date values.

In the above example, essentially we are just creating a new date object using the values from the datetime object.

Using the datetime.date() function to remove time from datetime in Python

The date() function takes a datetime object and returns the date object using the values of the provided datetime object. This way, we remove time from datetime in Python.

This is similar to what we achieved in the second part of the previous method.

Using the datetime.strftime() function to remove time from datetime in Python

We can also use the strftime() function to remove time from datetime in Python. The strftime() function is used to return a string based on a datetime object. We need to specify the format of the required values to extract them.

To remove time from datetime in Python, we will use the %Y-%m-%d format within the function.

Using the pandas library to remove time from datetime in Python

The pandas library is used to work with DataFrame objects in Python. Often, these DataFrames contain date and time values so a submodule to handle date and time values was added to this library.

The to_datetime() function is used to create a timestamp object that represents date and time values. We can extract the date from this object using the date() method.

This will remove time from datetime in Python.

Conclusion

To wrap up, we discussed how to remove time from datetime in Python. To do this, we need to display only the date part from the datetime object.

In the first method, we used the individual attributes from the datetime object to create a new string and a date object. The second method uses the date() function to return the date object.

The third method also returns a string using the strftime() function and removes the time from the datetime object. An additional method involving the pandas library is also displayed at the end.

Источник

Remove Time from Datetime in Python

To remove the time from a datetime object in Python, convert the datetime to a date using date().

import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = currentDateTime.date() print(currentDateTime) print(currentDateWithoutTime) #Output: 2022-03-05 15:33:11.283729 2022-03-05

You can also use strftime() to create a string from a datetime object without the time.

import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = currentDateTime.strftime('%Y-%m-%d') print(currentDateTime) print(currentDateWithoutTime) #Output: 2022-03-05 15:33:11.283729 2022-03-05

When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display the current date.

With Python, we can easily remove the time from a datetime variable.

To get rid of the time, we just need to convert the datetime to a date. To do so, use the datetime date() function.

Below is a simple example of how to get remove the time from a datetime in Python.

import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = currentDateTime.date() print(currentDateTime) print(currentDateWithoutTime) #Output: 2022-03-05 15:33:11.283729 2022-03-05

Using strfttime to Remove the Time from Datetime in Python

The Python strftime() function is very useful when working with date and datetime variables. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.

We can use strftime() to easily remove the time from datetime variables.

For example, if you want to print out the date in the format “YYYY-MM-DD”, we pass “%Y-%m-%d” to strfttime() and no time is printed.

Below is a simple Python example of how to print the date without time using strftime().

import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = currentDateTime.strftime('%Y-%m-%d') print(currentDateTime) print(currentDateWithoutTime) #Output: 2022-03-05 15:33:11.283729 2022-03-05

Hopefully this article has been useful for you to learn how to use Python to remove the time from datetime variables.

  • 1. Multiple Condition While Loops in Python
  • 2. pandas to_pickle – Write DataFrame to Pickle File
  • 3. Python Check if Object Has Attribute
  • 4. How to Save and Use Styles from Existing Word File With python-docx
  • 5. Using Python to Check If Variable is Not None
  • 6. How to Check if Variable Exists in Python
  • 7. Are Tuples Mutable in Python? No, Tuples are not Mutable
  • 8. Python Add Months to Datetime Variable Using relativedelta() Function
  • 9. Using Python to Count Number of Lines in String
  • 10. Using Python to Replace Multiple Spaces with One Space in String

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

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