How to convert datetime.date to UTC timestamp in Python

0 votes

I need to convert date to UTC timestamps to be used inside Javascript.

The following code does not work:

>>> d = datetime.date(2018,10,31)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2018, 10, 31, 23, 0)

Converting the date object first to datetime also does not help. I tried the example at this link from, but:

from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)

and now either:

mktime(utc.localize(input_date).utctimetuple())

or

mktime(timezone('US/Eastern').localize(input_date).utctimetuple())

does work.

Oct 31, 2018 in Python by findingbugs
• 3,140 points
1,344 views

1 answer to this question.

0 votes

In Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

And for an aware dt:

timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
answered Oct 31, 2018 by Priyaj
• 56,160 points

Related Questions In Python

0 votes
1 answer

How to convert a Pandas GroupBy object to DataFrame in Python

g1 here is a DataFrame. It has a hierarchical index, ...READ MORE

answered Nov 12, 2018 in Python by Nymeria
• 3,500 points
3,667 views
0 votes
1 answer

How to parse date/time string with timezone abbreviated name in Python?

The parse() function in dateutil can't handle ...READ MORE

answered Nov 27, 2018 in Python by Nymeria
• 3,500 points
134 views
+1 vote
1 answer

How to convert records from csv to a list in Python?

If you are using Python 3.x then ...READ MORE

answered Jun 25 in Python by Arvind
• 1,530 points

edited Jun 26 by Kalgi 29 views
+3 votes
5 answers

How to read multiple data files in python

Firstly we will import pandas to read ...READ MORE

answered Apr 6, 2018 in Python by DeepCoder786
• 1,700 points
1,060 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 133 views
0 votes
1 answer

How to convert date string to date object in python?

Use this :-  >>> datetime.datetime.strptime('24052010 ...READ MORE

answered Oct 22, 2018 in Python by Priyaj
• 56,160 points
77 views
0 votes
1 answer

How to Convert usual text to executable machine code in python

what you are looking for is a ...READ MORE

answered Oct 1, 2018 in Python by Priyaj
• 56,160 points
31 views