- Python Datetime to Seconds
- Table of contents
- What is Epoch time
- How to convert datetime to Seconds in Python
- Example: Datetime to Seconds
- Datetime to seconds using timestamp()
- Datetime to seconds using a calendar module
- Seconds/epoch to Datetime
- Converting epoch time with milliseconds to datetime
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- How to convert a datetime object to seconds?
- Date in Python
- Convert Datetime Object to Seconds
- Example: The total_seconds() Method
- Example: Use timestamp() method
- Example: Use calender.timegm() method
- Conclusion
Python Datetime to Seconds
This article will teach you how to convert datetime to seconds in Python.
After reading this Python article, you’ll learn:
- How to convert datetime to seconds ( number of seconds since epoch).
- How to convert seconds to datetime
Table of contents
What is Epoch time
When we try to convert datetime to seconds, we need to understand the epoch time first.
In computing, an epoch time is a date and time from which a computer measures system time. It is a starting point or fixed moment in time used to calculate the number of seconds elapsed. The computer’s datetime is determined according to the number of seconds elapsed since the epoch time.
Epoch time is also known as POSIX time or UNIX time. For example, in most UNIX versions, the epoch time starts at 00:00:00 UTC on 1 January 1970.
So when we convert datetime to seconds we will get the number of seconds since epoch. It means the elapsed seconds between input datetime and epoch time (00:00:00 UTC on 1 January 1970).
How to convert datetime to Seconds in Python
Let’s assume you have a datetime (2018,10,22) in a UTC format and you want to calculate the number of seconds since the epoch. The below steps shows two ways to convert datetime to seconds.
- Import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
- Subtract the input datetime from the epoch time To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.
- Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds. This method returns a float value representing even fractions of a second.
Example: Datetime to Seconds
from datetime import datetime # input datetime dt = datetime(2018, 10, 22, 0, 0) # epoch time epoch_time = datetime(1970, 1, 1) # subtract Datetime from epoch datetime delta = (dt - epoch_time) print('Datetime to Seconds since epoch:', delta.total_seconds())
Datetime to Seconds since epoch: 1540166400.0
Datetime to seconds using timestamp()
A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred. This information could be accurate to the microseconds. It is a POSIX timestamp corresponding to the datetime instance.
The below code shows how to convert datetime to seconds using the timestamp() method. This method will only be useful if you need the number of seconds from epoch (1970-01-01 UTC). It returns a number of elapsed seconds since epoch as a float value representing even fractions of a second.
from datetime import datetime # input datetime dt = datetime(2018, 10, 22, 0, 0) print('Seconds since epoch:', dt.timestamp())
Seconds since epoch: 1540146600.0
Note that different timezones have an impact on results. Therefore one should consider converting datetime to UTC before converting it to seconds.
To get an accurate result, you should use the UTC datetime. If your datetime isn’t in UTC already, you’ll need to convert it before using it or attach a tzinfo class with the proper timezone offset. Add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.
Don’t use strptime to convert datetime to seconds using the %s attribute because Python doesn’t support the %s attribute. If you use it, Python will use your systems’ strftime, which uses your local timezone, and you will get an inaccurate result. See docs.
Datetime to seconds using a calendar module
The calendar module provides the timegm() method that returns the corresponding Unix timestamp value, assuming an epoch of 1970 and the POSIX encoding.
- import clenadar module
- Use the datetime.timetuple() to get the time tuple from datetime.
- Next, pass the time tuple to the calendar.timegm() method to convert datetime to seconds.
import calendar from datetime import datetime # input datetime dt = datetime(2018, 10, 22, 0, 0) print('Datetime to seconds:', calendar.timegm(dt.timetuple()))
Datetime to seconds: 1540166400
- This method strips off the fractions of a second.
- The calendar’s approch has no way to specify a timezone. If input datetime is aware instance and used a timezone different from the system’s timezone, the result would not be correct (the timezone gets lost in the timetuple() call). To get the correct answer for an ‘aware’ datetime, you can use awaredt.timestamp() .
Seconds/epoch to Datetime
If you want to convert the number of seconds since the epoch to a datetime object, use the fromtimestamp() method of a datetime class.
from datetime import datetime # seconds ts = 1540146600.0 # convert seconds to datetime dt = datetime.fromtimestamp(ts) print("datetime is:", dt)
datetime is: 2018-10-22 00:00:00
Converting epoch time with milliseconds to datetime
If you want to convert the milliseconds to a datetime object, use the strptime() method of a datetime class. Use the %f format code for parsing.
from datetime import datetime seconds = 1536472051807 / 1000.0 dt = datetime.fromtimestamp(seconds).strftime('%Y-%m-%d %H:%M:%S.%f') print('Datetime is:', dt)
Datetime is: 2018-09-09 11:17:31.807000
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
How to convert a datetime object to seconds?
In this article, we will learn to convert datetime object to seconds in Python. We will use some built-in modules available and some custom codes as well to see them working. Let’s first have a quick look over what are dates in Python.
Date in Python
In Python, we can work on Date functions by importing a built-in module datetime available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. It requires date, month, and year values to compute the function. Date and time functions are compared like mathematical expressions between various numbers.
Convert Datetime Object to Seconds
In Python, the date and time module provides various functions for the manipulation of dates. We can also convert a datetime object into seconds by applying mathematical operations. For this conversion, datetime module provides total_seconds method, calender method and timestamp method to convert a datetime object to seconds. The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn’t in UTC already, you will need to convert it before you use it.
Example: The total_seconds() Method
1. datetime.strptime() formats the input timestamp into hh:mm:ss.
2. datetime.datetime() takes a year, month, day as arguments to create datetime object.
3. datetime.total_seconds() returns the total number of seconds.
The below example takes the time string into the acceptable format of hh:mm:ss. Python provides an operation on datetime to compute the difference between two dates. It finds the difference between the initial datetime object and the datetime object created from the time string. The value returned is a timedelta object from which we can use the function total_seconds() to get the value in seconds.
import datetime time = "01:01:09" date_time = datetime.datetime.strptime(time, "%H:%M:%S") a_timedelta = date_time - datetime.datetime(1900, 1, 1) seconds = a_timedelta.total_seconds() print(seconds)
Example: Use timestamp() method
Python 3 provides datetime.timestamp() method to easily convert the datetime object to seconds. This method will only be useful if you need the number of seconds from 1970-01-01 UTC. It returns a float value representing even fractions of a second. It is assumed that the datetime object represents the local time, i.e. it will be the number of seconds from the current time at your location to 1970-01-01 UTC.
from datetime import datetime #get current date dt = datetime.today() seconds = dt.timestamp() print(seconds)
Example: Use calender.timegm() method
Python 3 provides a standard library called calendar which has calendar.timegm() method to easily convert the datetime object to seconds. This method converts a datetime to seconds since Epoch i.e. 1970-01-01 UTC. As the above timestamp() method returns a float value, this method strips off the fractions of a second.
from datetime import datetime #get current date dt = datetime.today() seconds = dt.timestamp() print(seconds)
Conclusion
In this article, we learned to convert a datetime object into seconds format by using datetime module. We discussed the working of datetime functions using different code snippets.