
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Python Pandas - Construct a naive UTC datetime from a POSIX timestamp
- How do you convert a JavaScript date to UTC?
- Pandas - Convert a Timestamp object to a native Python datetime object
- How to convert timestamp string to datetime object in Python?
- How to convert timestamp to datetime in MySQL?
- How to convert MySQL datetime to Unix timestamp?
- How to convert TimeStamp to DateTime in Kotlin?\n
- How do I print a Python datetime in the local timezone?
- Python Pandas - Return a new Timestamp representing UTC day and time
- Convert the value of the current DateTime object to UTC in C#
- In MySQL, how can I convert a number of seconds into TIMESTAMP?
- How do I re-format datetime in MySQL?
- How to convert date to datetime in Python?
- How to convert DateTime to a number in MySQL?
- How do I convert a double into a string in C++?
Advertisements