Python3 Timestamp to unix time (with sometime milliseconds) - python

I'm trying to convert a timestamp to unix time.
Timestamp looks like this:
2018-01-16T20:26:16.35
So now I use this code:
timestamp = '2018-01-16T20:26:16.35'
ts = timestamp.replace("T", " ")
tsUnix = time.mktime(datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f").timetuple())
Sometime the api where get the timestamps from gives me the time without milliseconds.
It will result in a error, 'Does not match the format'. (Duh, %f is not in there)
Do I need to script a workaround or is there a function for this? And is there a better way to strip the "T" from the original timecode?

Here is one way to handle your issue, using try and except:
import time
import datetime
def get_ts_unix(ts):
try:
tsUnix = time.mktime(
datetime.datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%f").timetuple()
)
except ValueError:
tsUnix = time.mktime(
datetime.datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S").timetuple()
)
return tsUnix
Example:
timestamps = ['2018-01-16T20:26:16.35', '2018-01-16T20:26:16']
for ts in timestamps:
print("%-24s: %f" % (ts, get_ts_unix(ts)))
Output:
2018-01-16T20:26:16.35 : 1516152376.000000
2018-01-16T20:26:16 : 1516152376.000000

To skip the ts = timestamp.replace("T", " ") add a T in the format string
timestamp = '2018-01-16T20:26:16.35'
time.mktime(datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
# returns 1516130776.0
To fix the milliseconds you could use the python-dateutil package
from dateutil import parser
raw_timestamp = '2018-01-16T20:26:16.35'
parsed_time = parser.parse(raw_timestamp)
timestamp = parsed_time.timestamp()

Related

Add/substract timedelta to imported time

I am importing two time values (format "%H:%M:%S") into this function and I would like to add/subtract a buffer (check_period, usually a value of 5) to it. The timedelta works fine on the time values created in this function, but not for imported values. Any suggestions on how I can fix this?
Many thanks,
VBA Pete
def check_shuttertime(close_time,open_time,check_period):
neg_adj_current_time = datetime.datetime.now() - datetime.timedelta(hours=0, minutes=check_period+1)
neg_adj_current_time = neg_adj_current_time.strftime("%H:%M:%S")
pos_adj_current_time = datetime.datetime.now() + datetime.timedelta(hours=0, minutes=check_period+1)
pos_adj_current_time = pos_adj_current_time.strftime("%H:%M:%S")
close_time = close_time + datetime.timedelta(hours=0, minutes=check_period+1) #<-ERRROR OCCURS HERE
open_time = open_time - datetime.timedelta(hours=0, minutes=check_period+1) #<-ERRROR OCCURS HERE
current_time = datetime.datetime.now().strftime("%H:%M:%S")
If close_time and open_time are of type strings you will get an error stating that the + operator between a string and timedelta is not supported:
TypeError: can only concatenate str (not "datetime.timedelta") to str
The way to fix this would be to parse the string into a datetime before applying the addition. E.g. as follows:
import datetime
close_time="11:22:33"
new_close_time = datetime.datetime.strptime(close_time, "%H:%M:%S") + datetime.timedelta(minutes=5)
print(new_close_time)
This would then yield:
1900-01-01 11:27:33

How to format a date value for Hubspot API using Python

I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:
from pytz import timezone, utc
from hubspot.crm.contacts import SimplePublicObject,
created_dt = # datetime from sqlalchemy query
utcdt = utc.localize(
datetime(
year=created_dt.year,
month=created_dt.month,
day=created_dt.day
)
)
ts = int(utcdt.timestamp())
props = SimplePublicObjectInput({"last_booking": str(ts)})
return client.crm.companies.basic_api.update(
hs_id, simple_public_object_input=props
)
this returns this error:
{"status":"error",
"message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
}
Ah, the answer was right there. Python timestamp returns the time in seconds, and HubSpot expects milliseconds. I just had to multiply by 1000:
ts = int(utcdt.timestamp()*1000)
now all looks good.
did you try adding hours and minutes to your datetime call
datetime(
year=created_dt.year,
month=created_dt.month,
day=created_dt.day,
hour=0,
minute=0
)
Use the Hubspot supported "sanetime" module: https://github.com/HubSpot/sanetime
Then to get a date:
yourdate = datetime.datetime.date()
hubspot_date = sanetime.time(yourdate )
Or if you do not want a dependency:
#convert datetime to UTC
your_utc_datetime = your_datetime.astimezone(pytz.UTC)
#replace time with midnight
your_utc_date_midnight = your_utc_datetime.replace(hour=0,minute=0,second=0, microsecond=0)
# convert to epoch (Python 3.3+)
your_hubspot_date = your_utc_date_midnight.timestamp()*1000

Convert timestamp to time only

I'm getting the calendar results from outlook, fetching only the Start time and the Subject of each calendar item.
import win32com, win32com.client
import datetime, time, pytz
def getCalendarEntries():
Outlook = win32com.client.Dispatch("Outlook.Application")
appointments = Outlook.GetNamespace("MAPI").GetDefaultFolder(9).Items
appointments.Sort("[Start]");
appointments.IncludeRecurrences = "True"
today = datetime.datetime.today().date().strftime("%Y-%d-%m")
tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%d-%m")
appointments = appointments.Restrict("[Start] >= '" +today+"' AND [Start] < '"+tomorrow+"'");
events={'Start':[],'Subject':[]}
for a in appointments:
events['Start' ].append(a.Start );
events['Subject'].append(a.Subject)
return events
calendar = getCalendarEntries();
n=len(calendar['Start']);
i=0;
while( n ):
print(
calendar['Start'][i] ,
calendar['Subject'][i]
);
n-=1;
i+=1;
This is the result, and it is correct:
$ py test_outlook.py
2019-12-06 10:00:00+00:00 test apointment
What I need now is to manipule this data above to get only the time: 10:00, so that I can do calculations and find out how much time there is until the event starts... like if it's 10min away, 1h away, etc.
I really have no idea on how to do it... anyone has any idea?
Uri Goren seems to have answered the question here: https://stackoverflow.com/a/38992623/8678978
You need to use strptime with the datetime format to get a date object, and then you can extract the time portion.
dateString = '2019-12-06 10:00:00+00:00'
dateObject = datetime.datetime.strptime(str[0:19], '%Y-%m-%d %H:%M:%S')
Now you have a date object and can get the time parts using:
dateObject.hour
dateObject.minute
dateObject.second
I am not sure what type getCalendarEntries returns. You can find out by adding an additional temporary line in your program:
print(type(calendar['Start'][i]))
If it is a datetime object, you can simply query the hour attribute:
hours = calendar['Start'][i].hour
If getCalendarEntries returns a POSIX timestamp, you can first convert it to a Python datetime object and then query the hour
dt = datetime.fromtimestamp(calendar['Start'][i])
hours = dt.hour
If it is a string, you can parse it using datetime.fromisoformat:
dt = datetime.datetime.fromisoformat(calendar['Start'][i])
hours = dt.hour

Converting unix timestamp (length 13) string to readable date in Python

i am tring to convert this unix timestamp 1491613677888 to readable date.
found here (stackoverflow) that python script:
import datetime
print(
datetime.datetime.fromtimestamp(
int("1284101485")
).strftime('%Y-%m-%d %H:%M:%S')
)
but when i put my timestamp there, i got that error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
now i see that the timestamp that i am using is 3 chars longer.
i checked it on this link:
http://www.unixtimestamp.com/index.php
and saw that its get the time out of it.
how can i do it using python?
(i am using python 3.4)
Your timestamp is not the 'classical' Unix timestamp (number of seconds since Jan 1st, 1970), as it is expressed in milliseconds.
You can translate it like this:
import datetime
timestamp_with_ms = 1491613677888
# We separate the 'ordinary' timestamp and the milliseconds
timestamp, ms = divmod(timestamp_with_ms, 1000)
#1491613677 888
# We create the datetime from the timestamp, we must add the
# milliseconds separately
dt = datetime.datetime.fromtimestamp(timestamp) + datetime.timedelta(milliseconds=ms)
formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
print(formatted_time)
# 2017-04-08 03:07:57.888
Edit: I hadn't noticed that fromtimestamp accepts a float. So, we can simply do:
import datetime
timestamp_with_ms = 1491613677888
dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)
formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
print(formatted_time)
# 2017-04-08 03:07:57.888
Your timestamp is 3 characters longer AND is a standard unix timestamp? That would mean your timestamp is at least 40,000 years into the future from today. Otherwise, the last 3 characters may represent something else, like milliseconds but that doesn't explain the error you're seeing.
If they are the milliseconds, and seeing how you're not using them in the format string, I see no harm in simply stripping them.
standard_unix_ts = int("1284101485000"[:-3])
EDIT Taking into account the comment of #cdarke, I'd suggest this instead:
standard_unix_ts = int("1284101485000"[:10])
EDIT 2 Following Gils comment
import datetime
not_unix_ts = "1284101485088"
unix_ts, milliseconds = not_unix_ts[:10], not_unix_ts[10:]
dt = datetime.datetime.fromtimestamp(float(unix_ts))
FORMAT_STRING = '%Y-%m-%d %H:%M:%S'
print("%s and %s milliseconds" % (dt.strftime(FORMAT_STRING), milliseconds))

Formatting time from Google Calendar API with Python

I am trying to get an easy to read time format to list events from google calendar for the current day. I can pull in the data, but I'm having a problem formatting the data to be just the Hour and minute for both start time and end time.
I want to display the information in an easy to read list, so I want to drop the date and seconds and only display the time in order. I have tried several different methods including slicing and trying to convert into date time with no luck.
date = datetime.datetime.now()
tomorrow = date.today() + datetime.timedelta(days=2)
yesterday = date.today() - datetime.timedelta(days=1)
now = str
data = '{:%Y-%m-%d}'.format(date)
tdata = '{:%Y-%m-%d}'.format(tomorrow)
ydata = '{:%Y-%m-%d}'.format(yesterday)
def DateQuery(calendar_service, start_date=data, end_date=tdata):
print 'Date query for events on Primary Calendar: %s to %s' % (start_date, end_date,)
query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full')
query.start_min = start_date
query.start_max = end_date
feed = calendar_service.CalendarQuery(query)
for i, an_event in enumerate(feed.entry):
print '\'%s\'' % (an_event.title.text)
for a_when in an_event.when:
dstime = (a_when.start_time,)
detime = (a_when.end_time,)
print '\t\tEnd time: %s' % (dstime)
print '\t\tEnd time: %s' % (detime)
It prints like this
End time: 2013-03-23T04:00:00.000-05:00
and I would prefer it be
End time: 04:00
Using the dateutil module:
>>> import dateutil.parser
>>> dateutil.parser.parse('2013-03-23T04:00:00.000-05:00')
>>> dt = dateutil.parser.parse('2013-03-23T04:00:00.000-05:00')
>>> dt.strftime('%I:%M')
'04:00'
If you don't want to use dateutil, you an also parse the string using the specific format with strptime.

Categories

Resources