Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Convert DateTime to UNIX Timestamp in Python ?

  • Last Updated : 23 Aug, 2021

The Unix timestmap is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970. In this article, we are going to see how to convert DateTime to Unix timestamp.

DateTime to Unix timestamp

For converting Python DateTime to Unix timestamp, we’ve imported a module called datetime and time in this example, and the variable date_time has been declared and assigned datetime. time/date (2021, 7, 26, 21, 20). The year is 2021, the month is 7, the day is 26, the hour is 21, and the minute is 20.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Code:



Python3




# importing datetime module
import datetime
import time
  
# assigned regular string date
date_time = datetime.datetime(2021, 7, 26, 21, 20)
  
# print regular python date&time
print("date_time =>",date_time)
  
# displaying unix timestamp after conversion
print("unix_timestamp => ",
      (time.mktime(date_time.timetuple())))

Output:

date_time => 2021-07-26 21:20:00
unix_timestamp =>  1627314600.0

Explanation:

Date and time manipulation classes are provided by the datetime module. The inverse function of local time is mktime(). It accepts a struct time or a full 9-tuple as an argument and returns a floating-point number to be compatible with time (). It is also used to convert a datetime to a Unix timestamp.

The timetuple() method of datetime.date objects return a time object.struct time. The struct time object is a named tuple that may be retrieved using either an index or by name. The year, month, and day fields of the named tuple returned by the timetuple() function will be set according to the date object, while the hour, minutes, and seconds fields will be set to zero.

DateTime to Unix timestamp with 13 digits

To obtain the current time, use datetime.now(). The timetuple() function of the datetime class returns the datetime’s properties as a named tuple. The timestamp with 13 digits must be multiplied by 1000.

Code:

Python3




import time
import datetime
  
presentDate = datetime.datetime.now()
unix_timestamp = datetime.datetime.timestamp(presentDate)*1000
print(unix_timestamp)

Output:

1628497724509.293

DateTime to Unix timestamp in UTC Timezone

The calendar module provides helpful calendar-related functions. The utc.now function returns the current time in the UTC timezone. In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime’s properties as a named tuple. To obtain the Unix timestamp, use print(UTC).



Code:

Python3




import calendar
import datetime
  
date = datetime.datetime.utcnow()
utc_time = calendar.timegm(date.utctimetuple())
print(utc_time)

Output:

1628497783

DateTime to Unix timestamp milliseconds

The datetime.now() function is used to obtain the current time. The mktime method is a time method that is the inverse function of local time; it is used to convert datetime to Unix timestamp milliseconds. The timetuple() function of the datetime class returns the datetime’s properties as a named tuple. To obtain the time in milliseconds, multiply it by 1000.

Code:

Python3




import datetime
import time
  
ms = datetime.datetime.now()
print(time.mktime(ms.timetuple()) * 1000)

Output:

1628497823000.0

Datetime.date to Unix timestamp

time.date() is a function that accepts just dates. In this case, 2021 is the year, 8 is the month, and 6 is the day. mktime() is a time method that is the inverse function of local time; it is used to convert dates to Unix timestamps.

Code:

Python3




import datetime
import time
  
datetime = datetime.date(2021, 8, 6)
print("Unix_Time: ",
      (time.mktime(datetime.timetuple())))

Output:

Unix_Time:  1628188200.0

DateTime string to Unix timestamp

The date and time are supplied in string format in this case. Here, 8 denotes the month, 6 denotes the day, 2021 denotes the year, 05 denotes the hour, 54 denotes the minute, and 8 denotes the second. strptime() is a datetime module method that is used to convert strings to datetime and time objects. The timestamp() function returns the current time in the current location.

Code:

Python3




import datetime
  
date_example = "8/6/2021, 05:54:8"
date_format = datetime.datetime.strptime(date_example,
                                         "%m/%d/%Y, %H:%M:%S")
unix_time = datetime.datetime.timestamp(date_format)
print(unix_time)

Output:

1628209448.0

Unix timestamp to Python DateTime

The DateTime module in Python is used to deal with date and time-related issues in Python. The fromtimestamp() method is one of the functions included in this module. The date class’s function fromtimestamp() computes and returns the date corresponding to a specified timestamp. The allowed timestamp range extends from 1970 to 2038. If there are any leap seconds in the timestamp, the fromtimestamp() function ignores them.

To begin with, we import the datetime class from the datetime module. The UNIX value object is then stored in a variable. Then we use the datetime.fromtimestamp() method to retrieve the time and date.  

The strftime() function is another function in the datetime module. This function aids in the return of a DateTime in a particular format. This function is used to convert date and time objects to string representations. The format codes in the above code are %d, %m, %Y, %H, %M, and %S, which indicate days, months, years, hours, minutes, and seconds, respectively.

Code:

Python3




# importing datetime module
import datetime 
  
# assigned unix time
unix_time = 1627334400
  
date_time = datetime.datetime.fromtimestamp(unix_time)
  
# print unix time stamp
print("Unix_Time =>",unix_time)
  
# displaying date and time in a regular 
# string format
print("Date & Time =>" ,
      date_time.strftime('%Y-%m-%d %H:%M:%S'))

Output:

Unix_Time => 1627334400
Date & Time => 2021-07-27 02:50:00



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!