- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I convert a datetime to a UTC timestamp in Python?
You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time.
example
from datetime import timezone dt = datetime(2015, 10, 19) timestamp = dt.replace(tzinfo=timezone.utc).timestamp() print(timestamp)
Output
This will give the output −
1445212800.0
If you're on Python 2, then you can use the total_seconds() function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970.
example
from datetime import timezone dt = datetime(2015, 10, 19) timestamp = (dt - datetime(1970, 1, 1)).total_seconds() print(timestamp)
Output
This will give the output −
1445212800.0
Advertisements