-2

I have python date object like

datetime.date(2020, 3, 29) # d1, django DateField in database

Now i want to get UTC timestamp of that date object d1 at midnight

I searched a lot but nothing works.

I tried

d2 = datetime.combine(d1, datetime.min.time())
d2.timestamp() // This is localtimezone i want in UTC

Not sure why i need to add time

Gonda
  • 5
  • 2
  • use `datetime.utcnow()` for UTC time – Mohsen Apr 20 '20 at 06:42
  • @Mohsen that will only give me today , what if its some other date? can i do d1.utcnow() – Gonda Apr 20 '20 at 06:43
  • 1
    Does this answer your question? [How to convert local time string to UTC?](https://stackoverflow.com/questions/79797/how-to-convert-local-time-string-to-utc) – Prudhvi Apr 20 '20 at 06:47
  • @Prudhvi i tried all those , too complex to understand whats going on there – Gonda Apr 20 '20 at 06:54
  • the datetime objects in your database, in what timezone are they in? UTC? – FObersteiner Apr 20 '20 at 06:59
  • @MrFuppes its only dateField not datetime Django date field – Gonda Apr 20 '20 at 07:22
  • alright, I tried to provide a not too complicated answer below. working with date and time can be confusing, but stay on it. I think [this answer](https://stackoverflow.com/a/8778548/10197418) is worth having a look at. – FObersteiner Apr 20 '20 at 07:33

1 Answers1

0

assuming your date object d is in UTC, you could simply add midnight time (00:00:00) and timezone info UTC and then apply timestamp() method to get the desired timestamp. Example:

import datetime as dt

d = dt.date(2020, 3, 29)
ts_utc = dt.datetime.combine(d, dt.time(0,0,0), tzinfo=dt.timezone.utc).timestamp()
print(ts_utc)
# 1585440000.0

check = dt.datetime.utcfromtimestamp(ts_utc)
print(check)
# 2020-03-29 00:00:00

Note: it is important to set the timezone, otherwise, the timestamp() method assumes that the input is in the timezone that the machine you run this code on is set to!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72