Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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.

1 Answer

0 votes
by (25.1k points)

You cannot directly get a timestamp but you can get a timezone aware timestamp like this:

timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)

If you want to get a deeper understanding of python you can watch this youtube video: 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...