You can use date
and time
methods of the datetime
class to do so:
>>> from datetime import datetime
>>> d = datetime.now[]
>>> only_date, only_time = d.date[], d.time[]
>>> only_date
datetime.date[2015, 11, 20]
>>> only_time
datetime.time[20, 39, 13, 105773]
Here is the datetime
documentation.
Applied to your example, it can give something like this:
>>> milestone["only_date"] = [d.date[] for d in milestone["datetime"]]
>>> milestone["only_time"] = [d.time[] for d in milestone["datetime"]]
In this article, you will learn to convert timestamp to datetime object and datetime object to timestamp [with the help of examples].
It's pretty common to store date and time as a timestamp in a database. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC.
Example 1: Python timestamp to datetime
from datetime import datetime
timestamp = 1545730073
dt_object = datetime.fromtimestamp[timestamp]
print["dt_object =", dt_object]
print["type[dt_object] =", type[dt_object]]
When you run the program, the output will be:
dt_object = 2018-12-25 09:27:53 type[dt_object] =
Here, we have imported datetime
class from the datetime module. Then, we used datetime.fromtimestamp[]
classmethod which returns the local date and time [datetime object]. This object is stored in dt_object variable.
Note: You can easily create a string representing date and time from a datetime
object using
strftime[] method.
Example 2: Python datetime to timestamp
You can get timestamp from a datetime object using datetime.timestamp[]
method.
from datetime import datetime
# current date and time
now = datetime.now[]
timestamp = datetime.timestamp[now]
print["timestamp =", timestamp]
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Python has a module named DateTime to work with dates and times. We did not need to install it separately. It is pre-installed with the python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC.
Timestamp to DateTime object
You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.
Syntax:
fromtimestamp[timestamp, tz=None]
Example: Python timestamp to DateTime
Python3
from
datetime
import
datetime
timestamp
=
1545730073
dt_obj
=
datetime.fromtimestamp[
1140825600
]
print
[
"date_time:"
,dt_obj]
print
[
"type of dt:"
,
type
[dt_obj]]
Output:
date_time: 2006-02-25 05:30:00 type of dt_obj:
Here, we have imported the DateTime class from DateTime module. Then we have used datetime.fromtimestamp[] class method which returns the local DateTime.
To get a DateTime in a particular form in you can use strftime function. The strftime[] function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.
Example:
Python3
from
datetime
import
datetime
timestamp
=
1553367060
dt_obj
=
datetime.fromtimestamp[timestamp].strftime[
'%d-%m-%y'
]
print
[
"date:"
,dt_obj]
Output:
date: 24-03-19
In this article we will discuss different ways to get the current date & timestamp in python. Python provides a module datetime which has a class datetime. It provides a method now[]. It returns a datetime class object containing the current date & time
information in provided timezone. If no timezone is provided then returned object will contain the current date time information in local timezone. To use this we need to import datetime class from datetime module i.e. Let’s use this to get the current date & timestamp i.e. We can directly print this datetime object, it will display the data in readable format i.e. Output Now let’s access the member
variables of datetime object to fetch the current timestamp elements like month , year, hour etc. Output: Instead of accessing each member of datetime object & creating a string of timestamp, we can directly convert the datetime object to different string formats. For example, Let’s get the current timestamp & convert the datetime object to DD-MMM-YYYY [HH:MM::SS.MICROS] format i.e. Output: We will discuss datetime to string conversion in more details in next article. Advertisements Suppose we don’t want complete current timestamp, we are just interested in current date. How to do that ? datetime class in datetime module consists of 2 other classes i.e date & time class. We can get date object from a datetime object i.e. It contains the date part of the current timestamp, we
can access it’s member variables to get the fields or we can directly and we can also print the object too i.e.Get the current date & time using datetime.now[]
datetime.now[tz=None]
from datetime import datetime
# Returns a datetime object containing the local date and time
dateTimeObj = datetime.now[]
print[dateTimeObj]
2018-11-18 09:32:36.435350
# Access the member variables of datetime object to print date & time information
print[dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day]
print[dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond]
2018 / 11 / 18
9 : 32 : 36 . 435350
# Converting datetime object to string
dateTimeObj = datetime.now[]
timestampStr = dateTimeObj.strftime["%d-%b-%Y [%H:%M:%S.%f]"]
print['Current Timestamp : ', timestampStr]
Current Timestamp : 18-Nov-2018 [09:32:36.435350]
Get the current Date only
dateTimeObj = datetime.now[]
# get the date object from datetime object
dateObj = dateTimeObj.date[]
# Access the member variables of date object to print print[dateObj.year, '/', dateObj.month, '/', dateObj.day] # Print the date object print[dateObj]
Output:
9 : 37 : 55 . 574360 09:37:55.574360
or we can convert it to string too i.e.
# Converting date object to string dateStr = dateObj.strftime["%b %d %Y "] print[dateStr]
Output:
Nov 18 2018
Get the current Time only
Now Suppose we are just interested in current time of today. How to do that?
As datetime module provides a datetime.time class too. We can get time object from a datetime object i.e.
# Returns a datetime object containing the local date and time dateTimeObj = datetime.now[] # get the time object from datetime object timeObj = dateTimeObj.time[]
It contains the time part of the current timestamp, we can access it’s member variables to get the fields or we can directly and we can also print the object too i.e.
# Access the member variables of time object to print time information print[timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond] # It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too print[timeObj]
Output:
9 : 44 : 41 . 921898 09:44:41.921898
or we can convert it to string too i.e.
timeStr = timeObj.strftime["%H:%M:%S.%f"]
Contents of timeStr will be,
09:44:41.921898
Python provides a module time & it has a function time[] that returns the number of seconds that have elapsed since epoch i.e. January 1, 1970 i.e.
# Get the seconds since epoch secondsSinceEpoch = time.time[]
Convert seconds since epoch to struct_time i.e.
# Convert seconds since epoch to struct_time timeObj = time.localtime[secondsSinceEpoch]
Now let’s access the member variables of struct_time object to create current timestamp in string format i.e.
# get the current timestamp elements from struct_time object i.e. print['Current TimeStamp is : %d-%d-%d %d:%d:%d' % [ timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec]]
Output:
Current TimeStamp is : 18-11-2018 9:44:41
Get Current Timestamp using time.ctime[]
time module has another function time.ctime[] i.e.
def ctime[seconds=None]
It accepts the seconds since epoch and convert them into a readable string format. If seconds are not passed it will take current timestamp i.e.
timeStr = time.ctime[] print['Current Timestamp : ', timeStr]
Output:
Current Timestamp : Sun Nov 18 09:44:41 2018
Complete executable example is as follows,
import time from datetime import datetime def main[]: print['*** Get Current date & timestamp using datetime.now[] ***'] # Returns a datetime object containing the local date and time dateTimeObj = datetime.now[] # Access the member variables of datetime object to print date & time information print[dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day] print[dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond] print[dateTimeObj] # Converting datetime object to string timestampStr = dateTimeObj.strftime["%d-%b-%Y [%H:%M:%S.%f]"] print['Current Timestamp : ', timestampStr] timestampStr = dateTimeObj.strftime["%H:%M:%S.%f - %b %d %Y "] print['Current Timestamp : ', timestampStr] print['*** Fetch the date only from datetime object ***'] # get the date object from datetime object dateObj = dateTimeObj.date[] # Print the date object print[dateObj] # Access the member variables of date object to print print[dateObj.year, '/', dateObj.month, '/', dateObj.day] # Converting date object to string dateStr = dateObj.strftime["%b %d %Y "] print[dateStr] print['*** Fetch the time only from datetime object ***'] # get the time object from datetime object timeObj = dateTimeObj.time[] # Access the member variables of time object to print time information print[timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond] # It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too print[timeObj] # Converting date object to string timeStr = timeObj.strftime["%H:%M:%S.%f"] print[timeStr] print['*** Get Current Timestamp using time.time[] ***'] # Get the seconds since epoch secondsSinceEpoch = time.time[] print['Seconds since epoch : ', secondsSinceEpoch] # Convert seconds since epoch to struct_time timeObj = time.localtime[secondsSinceEpoch] print[timeObj] # get the current timestamp elements from struct_time object i.e. print['Current TimeStamp is : %d-%d-%d %d:%d:%d' % [ timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec]] # It does not have the microsecond field print['*** Get Current Timestamp using time.ctime[] *** '] timeStr = time.ctime[] print['Current Timestamp : ', timeStr] if __name__ == '__main__': main[]
Output:
*** Get Current date & timestamp using datetime.now[] *** 2018 / 11 / 18 9 : 44 : 41 . 921898 2018-11-18 09:44:41.921898 Current Timestamp : 18-Nov-2018 [09:44:41.921898] Current Timestamp : 09:44:41.921898 - Nov 18 2018 *** Fetch the date only from datetime object *** 2018-11-18 2018 / 11 / 18 Nov 18 2018 *** Fetch the time only from datetime object *** 9 : 44 : 41 . 921898 09:44:41.921898 09:44:41.921898 *** Get Current Timestamp using time.time[] *** Seconds since epoch : 1542514481.9218981 time.struct_time[tm_year=2018, tm_mon=11, tm_mday=18, tm_hour=9, tm_min=44, tm_sec=41, tm_wday=6, tm_yday=322, tm_isdst=0] Current TimeStamp is : 18-11-2018 9:44:41 *** Get Current Timestamp using time.ctime[] *** Current Timestamp : Sun Nov 18 09:44:41 2018