- 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
- Get Current Time in Python (Different Formats & Timezones)
- Current Time in Python
- Current Time in Milliseconds
- Current Time in Seconds
- Get Current Local Date and Time
- Get Current Timezone
- Get Current Epoch/Unix Timestamp
- Current UTC Time
- Current ISO Time
- Current GMT Time
- Get Current Years, Months, Days, Hours, Minutes, and Seconds
- Further Reading
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
Get Current Time in Python (Different Formats & Timezones)
For example, here is a simple piece of code to get the current time:
from datetime import datetime now = datetime.now().strftime("%H:%M:%S") print(f"The time is ")
This displays the current time in HH:MM:SS format:
This is a comprehensive guide to getting the current time in Python.
You will learn how to get the current time in different formats and contexts in Python. For example, you’ll learn how to get the current time in milliseconds, in the Epoch format, and how to extract different time components from it.
Current Time in Python
Dealing with time is crucial in some Python programs. To make handling instances of time easier in your projects, Python has some useful libraries like time and datetime.
Read more about using the datetime module in Python.
Let’s take a complete look at how you can get the current time in Python using different timezones, formats, and such.
Current Time in Milliseconds
Milliseconds means one-thousandth (1/1000th) of a second.
To get the current time in milliseconds in Python:
import time t = time.time() t_ms = int(t * 1000) print(f"The current time in milliseconds: ")
The current time in milliseconds: 1635249073607
Current Time in Seconds
To get the current time in seconds in Python:
import time t = time.time() t_s = int(t) print(f"The current time in seconds: ")
The current time in seconds: 1635249118
Get Current Local Date and Time
To get the current local date and time in Python:
- Import the datetime class from the datetime module.
- Ask for the current time by datetime.now().
from datetime import datetime now = datetime.now() print(f"The timestamp is ")
The timestamp is 2021-10-26 14:53:37.807390
Get Current Timezone
To get the current local timezone in Python:
- Import the datetime class from the datetime module.
- Get the current time.
- Convert the current time to time that stores timezone information.
- Get your local timezone from the timezone information.
from datetime import datetime now = datetime.now() now_with_tz = now.astimezone() my_timezone = now_with_tz.tzinfo print(my_timezone)
I am in the EEST timezone (Eastern European Summer Time), so the above code gives me:
Get Current Epoch/Unix Timestamp
The epoch time/UNIX time refers to how many seconds have passed since Jan 1st, 1970.
To get the current epoch/UNIX timestamp in Python:
import time t_epoch = time.time() print(f"The epoch time is now: ")
The epoch time is now: 1635251715.9572039
Current UTC Time
To get the current time in UTC time format in Python:
from datetime import datetime, timezone now = datetime.now(timezone.utc) print(f"Current UTC Time: ")
Current UTC Time: 2021-10-26 12:01:54.888681+00:00
Current ISO Time
The ISO 8601 (International Organization for Standardization) is a standard way to express time.
ISO 8601 follows the format T[hh]:[mm]:[ss].
To get the current time in ISO format in Python:
- Import the datetime class from the datetime module.
- Convert current time to ISO format.
from datetime import datetime ISO_time = datetime.now().isoformat() print(f"Current DateTime in ISO: ")
Current DateTime in ISO: 2021-10-26T15:02:36.635934
Current GMT Time
The GMT or Greenwich Mean Time is the solar time observed in Greenwich, London.
To get the current GMT time in Python:
- Import gmttime, strftime from the time module.
- Get the GMT time with the gmttime() function.
- Format the time.
from time import gmtime, strftime now_GMT = strftime("%a, %d %b %Y %I:%M:%S %p %Z", gmtime()) print("GMT time is now: " + now_GMT)
GMT time is now: Tue, 26 Oct 2021 12:10:09 PM UTC
Get Current Years, Months, Days, Hours, Minutes, and Seconds
To extract years, months, days, hours, minutes, and seconds in Python:
- Import the datetime class from the datetime module.
- Get the current date object.
- Pull the time components from the current date object.
from datetime import datetime now = datetime.now() print(f"Year: ") print(f"Month: ") print(f"Day: ") print(f"Hour: ") print(f"Minute: ") print(f"Second: ")
Year: 2021 Month: 10 Day: 26 Hour: 15 Minute: 13 Second: 48
This completes the guide! I hope you find it useful and learned something new. Thanks for reading. Happy coding!