简体   繁体   中英

How to Convert a Date to UNIX Miliseconds at Midnight for Hubspot API

I am trying to input data into the Hubspot API using Python.

I have dates in the format of %m%d%Y. I need to convert this to UNIX time in milliseconds. I have that part set, I believe, using the code below.

t = '09/02/2020'
t = datetime.strptime(t, "%m/%d/%Y").strftime("%Y-%m-%dT%H:%M:%S.%f")
ts = time.mktime(datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
ts * 10000
ts = int(ts)

The end result for this example is

t= 2020-09-02T00:00:00.000000

ts = 1599019200

If I take the result of ts and put it into https://www.unixtimestamp.com/index.php it appears to convert to 09/02/2020 @ 4:00am (UTC)

However Hubspot says "Date properties will only store the date, and must be set to midnight UTC for the date you want."

Where I am lost is, I don't know how to set this up so that the result is always set to midnight UTC and I cannot find any examples that would help me do that.

Can anyone help explain how to do that?

There's datetime.timestamp() method which returns date in unixtime format, but if you'll take a look in docs of this method, you'll see:

Note: There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc :

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

or by calculating the timestamp directly:

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

So, following docs solutions are:

from datetime import datetime, timezone, timedelta

t = "09/02/2020"
ts = datetime.strptime(t, "%m/%d/%Y").replace(tzinfo=timezone.utc).timestamp()
# OR
ts = (datetime.strptime(t, "%m/%d/%Y") - datetime(1970, 1, 1)).total_seconds()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM