Trending December 2023 # Timestamp To Date In Python # Suggested January 2024 # Top 21 Popular

You are reading the article Timestamp To Date In Python updated in December 2023 on the website Minhminhbmm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Timestamp To Date In Python

Introduction to Timestamp to Date in Python

The timestamp to date is the conversion of the encoded numerical values into data using python. The timestamp is an encoded or encrypted sequence of the information and converts it into date and time. The python converts from timestamp to date using the installed module or method. It is a method to convert digital information into date using a python programming language. The python language has installed a feature to change timestamp to date using the method. It is a transformation in python technology to keep maintain application information.

Syntax of Timestamp to Date in Python

Given below is the syntax mentioned:

The timestamp to date converts from 1 January 1970, at UTC.

The basic syntax of the timestamp to date method is below:

fromtimestamp()

The “fromtimestamp” method helps to convert into date and date-time. The object of the value keeps inside of the method.

The basic syntax of the timestamp to date with value is below:

fromtimestamp(timestamp value)

Or

fromtimestamp(timestamp value, tz = none)

The “fromtimestamp” method helps to convert into a date. The “timestamp value” is a sequence of the information to convert into a date. The “tz” specifies the time zone of the timestamp. This function is optional.

The syntax of the timestamp to date using python language is below:

datetime.fromtimestamp(timestamp value)

Or

datetime.fromtimestamp(timestamp object)

The “datetime” is a python module to convert into a date, date-time, timestamp, etc. The “fromtimestamp” method helps to convert into a date. The “timestamp value” is an encoded sequence of the information to convert into a date. The python installed the datetime module by default. You do not need to install third software for conversion. The datetime uses either object or value inside of the “fromtimestamp” method.

The syntax of the timestamp to date conversion shows below:

datetime.fromtimestamp(objtmstmp).strftime('%d - %m - %y')

The “datetime” is a python module to convert into date. The “strftime” function shows the only date as per requirement. The function uses to date, month, and time as per the required format.

How to Convert Timestamp to Date in Python?

Install python software or use online IDE for coding.

The following link helps to download python software.

Create a python file using the .py extension. Then, start to write python code.

Filename: main.py

Import the “datetime” file to start timestamp conversion into a date.

from datetime import datetime

Create an object and initialize the value of the timestamp.

objtmstmp = 14590157322

Use the ” fromtimestamp ()” method to place either data or object.

objectdate = datetime.fromtimestamp(objtmstmp)

Or

objectdate = datetime.fromtimestamp(14590157322)

Print the date after conversion of the timestamp.

print(" date" , objectdate)

If you require the type of date, then print the date type of the python.

print("type of date object =", type(objectdate))

Combine the working procedure of the timestamp to date in the python.

from datetime import datetime objtmstmp = 14590157322 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate)) Examples of Timestamp to Date in Python

Given below are the examples of Timestamp to Date in Python:

Example #1

The timestamp to date convert for the 1970 year example and output.

Code:

from datetime import datetime objtmstmp = 100043 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #2

The timestamp to date convert for the 2000 year example and output.

Code:

from datetime import datetime objtmstmp = 1000000000 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #3

The timestamp to date convert at the 1970 year example and output.

Code:

from datetime import datetime objtmstmp = 2500000000 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #4

The timestamp to date convert with four-digit value example and output.

Code:

from datetime import datetime objtmstmp = 1000 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #5

The timestamp to date convert with a five-digit value example and output.

Code:

from datetime import datetime objtmstmp = 10005 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #6

The timestamp to date converts to change date example and output.

Code:

from datetime import datetime objtmstmp = 1000641 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #7

The timestamp to date converts to change month example and output.

Code:

from datetime import datetime objtmstmp = 10006416 objectdate = datetime.fromtimestamp (objtmstmp) print ("timestamp to date conversion.") print (" date" , objectdate) print ("type of date object =", type (objectdate))

Output:

Example #8

The timestamp to date converts to change current date example and output.

Code:

import datetime; print ("Display current time") current_time = datetime.datetime.now() print ("current time:-", current_time) print ("Display timestamp") time_stamp = current_time.timestamp() print ("timestamp:-", time_stamp)

Output:

Example #9

The timestamp to date converts to change current date example and output.

Code:

from datetime import datetime objtmstmp = 1500000 objectdate = datetime.fromtimestamp(objtmstmp).strftime('%d - %m - %y') print ("timestamp to date conversion.") print (" date (date - month - year):" , objectdate) objectdate = datetime.fromtimestamp(objtmstmp).strftime('%y - %d - %m') print ("timestamp to date conversion.") print (" date (year - date - month):" , objectdate) objectdate = datetime.fromtimestamp(objtmstmp).strftime('%m - %d - %y') print ("timestamp to date conversion.") print (" date (month - date - year ):" , objectdate)

Output:

Conclusion

It helps to save date and time effortlessly in the database. The web application shows the date from the timestamp value using minimum code. The timestamp to date stores date and time together without complexion. It is used for updates, search date, and time without lengthy code.

Recommended Articles

This is a guide to Timestamp to Date in Python. Here we discuss the introduction, how to convert Timestamp to date in python? And examples. You may also have a look at the following articles to learn more –

You're reading Timestamp To Date In Python

How To Add Months To A Date In Javascript?

To add months to a date in JavaScript, you can use the Date.setMonth() method. JavaScript date setMonth() method sets the month for a specified date according to local time. This method takes two parameters first is the number of months and the second parameter is the number of days. The counting of the month is start from 0, for example, 0 represents January, 1 represents February … and so on.

Syntax Date.setMonth(monthsValue , [daysValue]);

Note − Parameters in the bracket are always optional.

Parameter Detail

monthsValue − An integer between 0 and 11, representing the months. Although we can also use the number bigger than 11 or less than 0. For example, -1 represents the last month of the previous year, and 12 represents the first month of the next year.

daysValue − An integer between 1 and 31, representing the day of the month. If you specify the daysValue parameter, you must also specify the monthsValue. You can also specify the number bigger than 31 and less than 1. For example, 0 represents the last day of the previous month, and -1 represents the day before the last day of the previous month. 32 represents the first day of the next month.

Algorithm

STEP 1 − First we get the current date or define a date and display it.

STEP 2 − Next we get the month of the current date using the getMonth() method.

STEP 3 − Define the number of months to be added.

STEP 4 − Set the month of the date using the setMonth() and display the updated date.

To add months into the Date object using the setMonth method first we get the value of months of the current Date using the getMonth( ) method and then add a number of months into it and pass the added value to the setMonth( ) method.

Example

In the below example, we add 3 months to the current date, and display the current date, and updated date. We use the getMonth() and setMonth() methods to get current month and set new month.

let dt = new Date(); document.getElementById(“currentTime”).innerText += dt let no_of_months = 3; dt.setMonth(dt.getMonth() + no_of_months) document.getElementById(“updatedTime”).innerText += dt;

In the example below, we take the date as “August 20, 2023 11:30:25”. We add two months to this date. We display both- the previous and updated dates.

let dt = new Date(“August 20, 2023 11:30:25”); document.getElementById(“currentTime”).innerText += dt let no_of_months = 2; dt.setMonth(dt.getMonth() + no_of_months) document.getElementById(“updatedTime”).innerText += dt;

Example

In this example, we are adding 4 months to the current Date. We display the current and updated date in MM/DD/YYYY format.

let ct = document.getElementById(“currentTime”) let currentDate = Date.now(); ct.innerText += new Date(currentDate).toLocaleDateString()

let ut = document.getElementById(“updatedTime”) function add() { let dt = new Date(); let no_of_months = 4; dt.setMonth(dt.getMonth() + no_of_months) ut.innerText += dt.toLocaleDateString(); }

Note − The formatting of the date is MM/DD/YYYY.

In this tutorial, we have discussed how to add months to a date. We use two methods for this purpose. One is the getMonth() method to get the month of the date. And second is the setMonth() method to set the month of the date with a new month.

Beginners Guide To Topic Modeling In Python

Introduction

Analytics Industry is all about obtaining the “Information” from the data. With the growing amount of data in recent years, that too mostly unstructured, it’s difficult to obtain the relevant and desired information. But, technology has developed some powerful methods which can be used to mine through the data and fetch the information that we are looking for.

One such technique in the field of text mining is Topic Modelling. As the name suggests, it is a process to automatically identify topics present in a text object and to derive hidden patterns exhibited by a text corpus. Thus, assisting better decision making.

What is Topic Modeling?

Topic modeling, an essential tool in statistics and natural language processing, encompasses a statistical model designed to reveal the abstract “topics” present in a set of documents. It serves as a powerful text-mining technique, enabling the discovery of concealed semantic structures within a body of text. By employing topic modeling, researchers can gain insights into the underlying themes and concepts embedded in the documents under investigation.

Topic Modelling is different from rule-based text mining approaches that use regular expressions or dictionary based keyword searching techniques. It is an unsupervised approach used for finding and observing the bunch of words (called “topics”) in large clusters of texts.

Topics can be defined as “a repeating pattern of co-occurring terms in a corpus”. A good topic model should result in – “health”, “doctor”, “patient”, “hospital” for a topic – Healthcare, and “farm”, “crops”, “wheat” for a topic – “Farming”.

Topic Models are very useful for the purpose for document clustering, organizing large blocks of textual data, information retrieval from unstructured text and feature selection. For Example – New York Times are using topic models to boost their user – article recommendation engines. Various professionals are using topic models for recruitment industries where they aim to extract latent features of job descriptions and map them to right candidates. They are being used to organize large datasets of emails, customer reviews, and user social media profiles.

So, if you aren’t sure about the complete process of topic modeling, this guide would introduce you to various concepts followed by its implementation in python.

Latent Dirichlet Allocation for Topic Modeling

There are many approaches for obtaining topics from a text such as – Term Frequency and Inverse Document Frequency. NonNegative Matrix Factorization techniques. Latent Dirichlet Allocation is the most popular topic modeling technique and in this article, we will discuss the same.

LDA assumes documents are produced from a mixture of topics. Those topics then generate words based on their probability distribution. Given a dataset of documents, LDA backtracks and tries to figure out what topics would create those documents in the first place.

LDA is a matrix factorization technique. In vector space, any corpus (collection of documents) can be represented as a document-term matrix. The following matrix shows a corpus of N documents D1, D2, D3 … Dn and vocabulary size of M words W1,W2 .. Wn. The value of i,j cell gives the frequency count of word Wj in Document Di.

Notice that these two matrices already provides topic word and document topic distributions, However, these distribution needs to be improved, which is the main aim of LDA. LDA makes use of sampling techniques in order to improve these matrices.

It Iterates through each word “w” for each document “d” and tries to adjust the current topic – word assignment with a new assignment. A new topic “k” is assigned to word “w” with a probability P which is a product of two probabilities p1 and p2.

For every topic, two probabilities p1 and p2 are calculated. P1 – p(topic t / document d) = the proportion of words in document d that are currently assigned to topic t. P2 – p(word w / topic t) = the proportion of assignments to topic t over all documents that come from this word w.

The current topic – word assignment is updated with a new topic with the probability, product of p1 and p2 . In this step, the model assumes that all the existing word – topic assignments except the current word are correct. This is essentially the probability that topic t generated word w, so it makes sense to adjust the current word’s topic with new probability.

After a number of iterations, a steady state is achieved where the document topic and topic term distributions are fairly good. This is the convergence point of LDA.

Parameters of LDA

Alpha and Beta Hyperparameters – alpha represents document-topic density and Beta represents topic-word density. Higher the value of alpha, documents are composed of more topics and lower the value of alpha, documents contain fewer topics. On the other hand, higher the beta, topics are composed of a large number of words in the corpus, and with the lower value of beta, they are composed of few words.

Number of Topics – Number of topics to be extracted from the corpus. Researchers have developed approaches to obtain an optimal number of topics by using Kullback Leibler Divergence Score. I will not discuss this in detail, as it is too mathematical. For understanding, one can refer to this[1] original paper on the use of KL divergence.

Number of Topic Terms – Number of terms composed in a single topic. It is generally decided according to the requirement. If the problem statement talks about extracting themes or concepts, it is recommended to choose a higher number, if problem statement talks about extracting features or terms, a low number is recommended.

Number of Iterations / passes – Maximum number of iterations allowed to LDA algorithm for convergence.

You can learn topic modeling in depth  here.

Running in python Preparing Documents

Here are the sample documents combining together to form a corpus.

Cleaning and Preprocessing

Cleaning is an important step before any text mining task, in this step, we will remove the punctuations, stopwords and normalize the corpus.



Preparing Document-Term Matrix Running LDA Model

```

Results

Each line is a topic with individual topic terms and weights. Topic1 can be termed as Bad Health, and Topic3 can be termed as Family.

Tips to improve results of topic modeling

The results of topic models are completely dependent on the features (terms) present in the corpus. The corpus is represented as document term matrix, which in general is very sparse in nature. Reducing the dimensionality of the matrix can improve the results of topic modelling. Based on my practical experience, there are few approaches which do the trick.

1. Frequency Filter – Arrange every term according to its frequency. Terms with higher frequencies are more likely to appear in the results as compared ones with low frequency. The low frequency terms are essentially weak features of the corpus, hence it is a good practice to get rid of all those weak features. An exploratory analysis of terms and their frequency can help to decide what frequency value should be considered as the threshold.

Note: If you want to learn Topic Modeling in detail and also do a project using it, then we have a video based course on NLP, covering Topic Modeling and its implementation in Python.

Topic Modelling for Feature Selection

Sometimes LDA can also be used as feature selection technique. Take an example of text classification problem where the training data contain category wise documents. If LDA is running on sets of category wise documents. Followed by removing common topic terms across the results of different categories will give the best features for a category.

Frequently Asked Questions

Q1. Why topic modeling is used?

A. Topic modeling is used to uncover hidden patterns and thematic structures within a collection of documents. It aids in understanding the main themes and concepts present in the text corpus without relying on pre-defined tags or training data. By extracting topics, researchers can gain insights, summarize large volumes of text, classify documents, and facilitate various tasks in text mining and natural language processing.

Q2. Which technique is used in topic modeling?

A. The technique commonly used in topic modeling is Latent Dirichlet Allocation (LDA). LDA is a generative probabilistic model that assigns words to topics and topics to documents, allowing the discovery of latent topics within a text corpus. It is a widely adopted method for topic modeling in natural language processing.

Q3. Is topic modelling a clustering technique?

A. While topic modeling involves the identification of clusters or groups of similar words within a body of text, it is not strictly considered a clustering technique in the traditional sense. Topic modeling aims to discover the underlying thematic structures or topics within a text corpus, which goes beyond the notion of clustering based solely on word similarity. It uses statistical models, such as Latent Dirichlet Allocation (LDA), to assign words to topics and topics to documents, providing a way to explore the latent semantic relationships in the data.

Endnotes

With this, we come to this end of tutorial on Topic Modeling. I hope this will help you to improve your knowledge to work on text data. To reap maximum benefits out of this tutorial, I’d suggest you practice the codes side by side and check the results.

Did you find the article useful? Share with us if you have done similar kind of analysis before. Do let us know your thoughts about this article in the box below.

References

Got expertise in Business Intelligence  / Machine Learning / Big Data / Data Science? Showcase your knowledge and help Analytics Vidhya community by posting your blog.

Related

How To Destroy An Object In Python?

When an object is deleted or destroyed, a destructor is invoked. Before terminating an object, cleanup tasks like closing database connections or filehandles are completed using the destructor.

The garbage collector in Python manages memory automatically. for instance, when an object is no longer relevant, it clears the memory.

In Python, the destructor is entirely automatic and never called manually. In the following two scenarios, the destructor is called −

When an object is no longer relevant or it goes out of scope

The object’s reference counter reaches zero.

Using the __del__() method

In Python, a destructor is defined using the specific function __del__(). For instance, when we run del object name, the object’s destructor is automatically called, and it then gets garbage collected.

Example 1

Following is an example of destructor using __del__() method −

class

destructor

:

def

__init__

(

self

)

:

print

(

“Object gets created”

)

;

def

__del__

(

self

)

:

print

(

“Object gets destroyed”

)

;

Object

=

destructor

(

)

;

del

Object

;

Output

Following is an output of the above code −

Object gets created Object gets destroyed

Note − The destructor in the code above is invoked either after the program has finished running or when references to the object are deleted. This indicates that the object’s reference count drops to zero now rather than when it leaves the scope.

Example 2

In the following example, we will use Python’s del keyword for destroying user-defined objects −

class

destructor

:

Numbers

=

10

def

formatNumbers

(

self

)

:

return

"@"

+

str

(

Numbers

)

del

destructor

print

(

destructor

)

Output

Following is an output of the above code −

NameError: name 'destructor' is not defined

We get the above error as ‘destructor’ gets destroyed.

Example 3

In the following example, we will see −

How to use the destructor

When we delete the object, how the destructor is called?

class

destructor

:

def

__init__

(

self

,

name

)

:

print

(

'Inside the Constructor'

)

self

.

name

=

name

print

(

'Object gets initialized'

)

def

show

(

self

)

:

print

(

'The name is'

,

self

.

name

)

def

__del__

(

self

)

:

print

(

'Inside the destructor'

)

print

(

'Object gets destroyed'

)

d

=

destructor

(

'Destroyed'

)

d

.

show

(

)

del

d

Output

We made an object using the code above. A reference variable called d is used to identify the newly generated object. When the reference to the object is destroyed or its reference count is 0, the destructor has been called.

Inside the Constructor Object gets initialized The name is Destroyed Inside the destructor Object gets destroyed Things to Keep in Mind About Destructor

When an object’s reference count reaches 0, the __del__ method is invoked for that object.

When the application closes or we manually remove all references using the del keyword, the reference count for that object drops to zero.

When we delete an object reference, the destructor won’t be called. It won’t run until all references to the objects are removed.

Example

Let’s use the example to grasp the above mentioned principles −

Using d = destructor(“Destroyed”), first create an object for the student class.

Next, give object reference d to new object d1, using d1=d

Now, the same object is referenced by both d and d1 variables.

After that, we removed reference d.

In order to understand that destructors only functions when all references to the object are destroyed, we added a 10 second sleep period to the main thread.

import

time

class

destructor

:

def

__init__

(

self

,

name

)

:

print

(

'Inside the Constructor'

)

self

.

name

=

name

print

(

'Object gets initialized'

)

def

show

(

self

)

:

print

(

'The name is'

,

self

.

name

)

def

__del__

(

self

)

:

print

(

'Inside the destructor'

)

print

(

'Object gets destroyed'

)

d

=

destructor

(

'Destroyed'

)

d1

=

d d

.

show

(

)

del

d time

.

sleep

(

10

)

print

(

'After sleeping for 10 seconds'

)

d1

.

show

(

)

Output

Destructors are only called, as you can see in the output, after all references to the objects are removed.

Additionally, the destructor is called once the program has finished running and the object is ready for the garbage collector. (That is, we didn’t explicitly use del d1 to remove object reference d1).

Inside the Constructor Object gets initialized The name is Destroyed After sleeping for 10 seconds The name is Destroyed

The Return Statement In Python

The return statement in python is an extremely useful statement used to return the flow of program from the function to the function caller. The keyword return is used to write the return statement.

Since everything in python is an object the return value can be any object such as – numeric (int, float, double) or collections (list, tuple, dictionary) or user defined functions and classes or packages.

The return statement has the following features –

Return statement cannot be used outside the function.

Any code written after return statement is called dead code as it will never be executed.

Return statement can pass any value implicitly or explicitly, if no value is given then None is returned.

Syntax

Following is the syntax of return statement in python –

def some_function(parameters): print(some_function) Example

Following is the simple example of return statement –

def welcome(str): return str + " from TutorialsPoint" print(welcome("Good morning")) Output

Following is an output of the above code –

Good morning from TutorialsPoint

The return statement is useful in multiple ways and the below sections discuss the different use case of return statement along with examples.

Use of return statement in Python

Functions are core of any programming language as they allow for code modularity thereby reducing program complexity. Functions can display the result within itself, but it makes the program complex, hence it is best to pass the result from all the functions to a common place.

It is in this scenario that the return statement is useful as it terminates the currently executing function and passes control of the program to the statement that invoked the function.

Example

In the below code the sum_fibonacci function is used to calculate the sum of the first 15 terms in the fibonacci series. After calculating the sum, it prints and returns the sum to the sum_result variable. This is to show that printing inside the function and returning the value give the same output.

# Defining function to calculate sum of Fibonacci series def sum_fibonacci(terms): first_term = 0 second_term = 1 sum_series = 0 # Finding the sum of first 15 terms of Fibonacci series for i in range(0, terms): sum_series = sum_series + first_term next_term = first_term + second_term first_term = second_term second_term = next_term # Printing the sum inside the function print("Sum of Fibonacci series inside the function is = {}".format(sum_series)) # Returning the sum using return statement return sum_series # Invoking the sum_fibonacci function sum_result = sum_fibonacci(15) print("Sum of Fibonacci series outside the function is = {}".format(sum_result)) Output

The output shows that the sum from inside the function using print statement and the sum from outside the function using return statement is equal.

Sum of Fibonacci series inside the function is = 986 Sum of Fibonacci series outside the function is = 986 Returning a function using return statement

In python, functions are first class objects which means that they can be stored in a variable or can be passed as an argument to another function. Since functions are objects, return statement can be used to return a function as a value from another function. Functions that return a function or take a function as an argument are called higher-order functions.

Example

In this example, finding_sum function contains another function – add inside it. The finding_sum function is called first and receives the first number as the parameter. The add function receives the second number as parameter and returns the sum of the two numbers to finding_sum function. The finding_sum function then returns the add function as a value to sum variable.

# Defining function to return sum of two numbers # Function to get the first number def finding_sum(num1): # Function to get the second number def add(num2): return num1 + num2 # return sum of numbers to add function return add # return value present in add function to finding_sum function sum = finding_sum(5) print("The sum of the two numbers is: {}".format(sum(10))) Output

The output of the program gives the sum of the two numbers – 5 and 10.

The sum of the two numbers is: 15 Returning None using return statement

Functions in python always return a value, even if the return statement is not written explicitly. Hence, python does not have procedures, which in other programming languages are functions without a return statement. If a return statement does not return a result or is omitted from a function, then python will implicitly return default value of None.

Explicit calling of return None should only be considered if the program contains multiple return statement to let other programmers know the termination point of the function.

Example

The program below gives a perfect illustration of using return None. In this program the check_prime() function is used to check if a list contains any prime numbers. If the list contains prime numbers, then all the prime numbers present in the list are printed. However, if there are no prime numbers in the list then None is returned, since this program contains multiple return statements, hence None is called explicitly.

def check_prime(list): prime_list = [] for i in list: counter = 0 for j in range(1, i): if i % j == 0: counter = counter + 1 if counter == 1: prime_list.append(i) if len(prime_list): return prime_list else: return None list = [4, 6, 8, 10, 12] print("The prime numbers in the list are: {}".format(check_prime(list))) Output

The output prints None since there are no prime numbers in the list.

The prime numbers in the list are: [4] Returning multiple values using return statement

The return statement in python can also be used to return multiple values from a single function using a ‘,’ to separate the values. This feature can be especially useful when multiple calculations need to be performed on the same dataset without changing the original dataset. The result from the return statement is a tuple of the values.

Example

In this example the built-in functions of the statistics library are used to compute the mean, median and mode which are returned using a single return statement showing how multiple values can be returned from a function.

import statistics as stat # Defining function to perform different statistical calculations def finding_stats(data): return stat.mean(data), stat.median(data), stat.mode(data) # returning multiple values list_numbers = [5, 7, 13, 17, 17, 19, 33, 47, 83, 89] print("The mean, median and mode of the data is: {}".format(finding_stats(list_numbers))) Output

The output gives the mean, median and mode of the dataset with type as tuple.

The mean, median and mode of the data is: (33, 18.0, 17)

How To Compare Only Date Part Without Comparing Time In Javascript?

While developing the applications, sometimes it needs to compare the only date. For example, you are developing some apps in which users must adhere to the deadline and pay for the subscription. If the user pays at any time on or before the end date of the subscription, the user will be able to use the subscription continues. Otherwise, you need to stop the subscription.

In this tutorial, we will learn to compare only the date part without comparing the time in JavaScript.

In the above cases, we need to compare the two dates without focusing on the time.

Approach 1: Using the setHours() Method

The simple logic to compare the only date parts is that remove the time from both date objects or set the time to 0. Here, we will create new dates and set their time to 0 so that when we make a comparison between the dates, it will compare the date part only as the time of both dates will be the same.

Syntax

Users can follow the below syntax to create new date objects and set the time to 0 for them.

let date1 = new Date(); date1.setHours(0, 0, 0, 0); let date2 = new Date( Date ); date2.setHours(0, 0, 0, 0);

We can use the following syntax to compare the two dates.

} else if ( date1 < dae2 ) { } else { } Parameters

Date − The date objects take the date as a parameter for that date, we want to initialize the new object of the Date() class.

The setHours() method takes 4 parameters, which are hours, minutes, seconds, and milliseconds respectively. We will set all to 0 on both dates.

Example

In the example below, we have created two new dates using the Date() class. After that, we have set hours 0 for both dates. We have created the function to compare the dates, which prints different outputs according to the date comparison. We have taken different dates to compare and observe the results in the example below.

let

output

=

document

.

getElementById

(

“output”

)

;

function

compareDates

(

date1

,

date2

)

{

if

(

date1

<

date2

)

{

}

else

{

}

}

let

date1

=

new

Date

(

)

;

date1

.

setHours

(

0

,

0

,

0

,

0

)

;

let

date2

=

new

Date

(

2002

,

06

,

21

)

;

date2

.

setHours

(

0

,

0

,

0

,

0

)

;

compareDates

(

date1

,

date2

)

;

date2

=

new

Date

(

)

;

date2

.

setHours

(

0

,

0

,

0

,

0

)

;

compareDates

(

date1

,

date2

)

;

We have set hours to 0 to compare the only date parts in JavaScript. However, users can extract the year, month, and date from the date object and compare them separately.

Approach 2: Using the toDateString() Method

The toDateString() method can be used to return the only date part of a JavaScript date. It returns the date part as a string. We can’t compare the string as date so we need to convert this string back to date. Now it sets the date with the time part to zero.

Syntax

We can apply the syntax to convert a date to date string and then convert back to date.

let date1 = new Date().toDateString(); date1 = new Date(date1) Example

In the example below, we create two dates and then convert them to strings using toDateString(). Then again convert these strings back to date. Now we compare these dates.

let

output

=

document

.

getElementById

(

“output”

)

;

function

compareDates

(

date1

,

date2

)

{

if

(

date1

<

date2

)

{

}

else

{

}

}

let

date1

=

new

Date

(

)

.

toDateString

(

)

;

date1

=

new

Date

(

date1

)

let

date2

=

new

Date

(

2002

,

06

,

21

)

.

toDateString

(

)

;

date2

=

new

Date

(

date2

)

compareDates

(

date1

,

date2

)

;

date2

=

new

Date

(

)

.

toDateString

(

)

;

date2

=

new

Date

(

date2

)

compareDates

(

date1

,

date2

)

;

Update the detailed information about Timestamp To Date In Python on the Minhminhbmm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!