Python 2.7 Converting standard unix timestamps to epoch time - python

I am trying to convert a time stamp of the format 20151021|133102[-0400/1] into an epoch time.
I want the code to run regardless of the native timezone of the machine it is running on, and be DST aware so the code will run over the switch to/from DST. I need the code to run under Python 2.7.x (ideally using only standard library modules so the code is portable.)
After wasting the afternoon googling, the best I have been able to do is:
time.mktime(time.strptime('20151021|133102','%Y%m%d|%H%M%S'))`
which does not allow me to incorporate either the offset, or the daylight savings flag.
I also tried the following:
time.mktime(time.strptime('20151021|133102-4000','%Y%m%d|%H%M%S%z'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y%m%d|%H%M%S%z'
but it seems that strptime does not allow the offset.
strptime does support:
time.mktime(time.strptime('20151021|133102EDT','%Y%m%d|%H%M%S%Z'))
but this means that I need to somehow convert the offset into a timezone abbreviation which seems sort of stupid--and might create an error depending on where the code is run.
I can't believe this isn't more straight forward given routine this problem should be. Any assistance would be much appreciated.

There are two steps:
parse the time string into a date/time object e.g., How to parse dates with -0400 timezone string in python? and
Parsing date with timezone from an email?
import time
time_string = "20151021|133102-0400"
tt = time.strptime(time_string[:15], "%Y%m%d|%H%M%S")
hours, minutes = divmod(int(time_string[16:]), 100)
utc_offset = (hours * 60 + minutes) * 60
if time_string[15] == '-':
utc_offset = -utc_offset
get "seconds since the Epoch" that corresponds to the date/time object: Converting datetime.date to UTC timestamp in Python
from calendar import timegm
posix_timestamp = timegm(tt) - utc_offset
I want the code to run regardless of the native timezone of the machine it is running on
time.mktime() expects local time as an input. Don't use it if the input time string does not represent local time. You also shouldn't use it if the time string has the utc offset (mktime() may produce a wrong result for ambiguous times or past/future dates).

First off you are identifying the numbers as a string. What I did was identify the string as an integer and then use datatime to convert into epoche time.
You'll need to remove the symbols not identified as an integer to have the following number listed above but the code below works for me on python 2.7
import datetime
conversion = datetime.datetime.fromtimestamp(int("20151021")).strftime('%Y-%m-%d %H:%M:%S')
print (conversion)

Weird. Works in Python3, but not Python2
>>> time.mktime(time.strptime('20151021|133102-0400', '%Y%m%d|%H%M%S%z'))
1445452262.0

Related

want to convert json timestamp into normal timestamp (CST Hrs) in python

I am downloading a json file containing timestamp using python . But the timestamp i am getting is below format
`2021-04-01T21:43:52.757Z`
Want to convert into normal timestamp (CST Hrs). I also see that the time is increased by 4 hours when i compare the report manually.
`4/1/2021 5:43:53 PM`
The above hours is 4 hrs less when i compare with json file entry. Please advise me.
You need to use python's datetime module to handle this. The Z in the string actually means time zone 0 or UTC time which is 6 hours ahead of CST not 4:
import datetime
date_object = datetime.datetime.strptime(
"2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)
date_object = date_object - datetime.timedelta(hours=6)
print(
f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)
Which will give this output:
4/1/2021 03:43:52 PM
have to use an f string if you want non zero padded dates because its not available in datetime according to the docs
You can use pytz module to deal with time zones directly and not hardcode them if you want. Or if you are on python 3.9 you can use timezone objects to create timezones yourself

Parsing date which may or may not contain milliseconds

So this question is more of best way to handle this sort of input in python. Here is an example of input date 2018-12-31 23:59:59.999999. The millisecond part may or may not be part of input.
I am currently using this code to convert this to datetime
input_ts = datetime.datetime.strptime(input_str, '%Y-%m-%dT%H:%M:%S.%f')
But the problem in this case is that it will throw an exception if input string doesn't contain milliseconds part i.e., 2018-12-31 23:59:59
In Java, I could have approached this problem in two ways. (its a pseudo explanation, without taking into account of small boundary checks)
(preferred approach). Check the input string length. if its less than 19 then it is missing milliseconds. Append .000000 to it.
(not preferred). Let the main code parse the string, if it throws an exception, then parse it with new time format i.e., %Y-%m-%dT%H:%M:%S
The third approach could be just strip off milliseconds.
I am not sure if python has anything built-in to handle these kind of situations. Any suggestions?
You could use python-dateutil library, it is smart enough to parse most of the basic date formats.
import dateutil.parser
dateutil.parser.parse('2018-12-31 23:59:59.999999')
dateutil.parser.parse('2018-12-31 23:59:59')
In case you don't want to install any external libraries, you could iterate over list of different formats as proposed in this answer.
from datetime import datetime # import datetime class from datetime package
dt = datetime.now() # get current time
dt1 = dt1.strftime('%Y-%m-%d %H:%M:%S') # converting time to string
dt3 = dt2.strptime('2018/5/20','%Y/%m/%d') # converting a string to specified time

django convert to date type (TypeError)

I'm trying to get data from excel cells (number format) and convert them to date type in Django 1.7.7:
import datetime as dt
birthdate =dt.date.fromtimestamp(sheet.row_values(idx)[63]).strftime('%Y-%m-%d')
but got this error:
File "t3_import2.py", line 46, in <module>
birthdate =dt.date.fromtimestamp(sheet.row_values(idx)[63]).strftime('%Y-%m-%d')
TypeError: a float is required
Why is it complaining when I explicitly cast it to float?
sheet.row_values(idx)[63] is not a float.
If I understand right, fromtimestamp expects a POSIX timestamp, which is a vector representing the number of seconds elapsed from a given time to the time/date it represents. I can't see what sheet.row_values(idx)[63] is from your post, but I'd bet Python it taking it as an int.
classmethod date.fromtimestamp(timestamp)¶
Return the local date
corresponding to the POSIX timestamp, such as is returned by
time.time(). This may raise ValueError, if the timestamp is out of the
range of values supported by the platform C localtime() function. It’s
common for this to be restricted to years from 1970 through 2038. Note
that on non-POSIX systems that include leap seconds in their notion of
a timestamp, leap seconds are ignored by fromtimestamp().
try this:
x = float(sheet.row_values(idx)[63])
birthdate = dt.date.fromtimestamp(x).strftime('%Y-%m-%d')

Retrieving free/busy status from microsoft outlook using python

I'm trying to retrieving free/busy status from outlook calender for particular person using python language.
here is my code for it.
import win32com.client
obj_outlook = win32com.client.Dispatch('Outlook.Application')
obj_Namespace = obj_outlook.GetNamespace("MAPI")
obj_Recipient = obj_Namespace.CreateRecipient("someone#domain.com")
str_Free_Busy_Data = obj_Recipient.FreeBusy("11-11-2013", 11)
print str_Free_Busy_Data
but I'm getting an error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
str_Free_Busy_Data = obj_Recipient.FreeBusy("11-11-2013", 11)
File "<COMObject CreateRecipient>", line 4, in FreeBusy
TypeError: an integer is required
So my question is Recipient.FreeBusy() method takes two mandatory arguments, Start Date and duration. Here 11 is the duration, which is an Integer. So why python is not able to identify the integer argument here and returning an TypeError.
Please help me in case I have done anything wrong (I'm still a newbie in python world).
Thanks in advance.
I looked up the method in MSDN.
http://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.outlook.recipient.freebusy(v=office.12).aspx
The syntax for the method takes 3 arguments.
string FreeBusy(
DateTime Start,
int MinPerChar,
Object CompleteFormat
)
The issue is that you're passing a string to the DateTime parameter. Instead you need to import the datetime library in your code and use a date parameter.
So, at the start of your code, try this.
import datetime
#Then declare the my_date variable as datetime.date.
my_date = datetime.date(2013,11,23)
str_Free_Busy_Data = obj_Recipient.FreeBusy(my_date, 11)
The first parameter to FreeBusy is a Date object. Pywin won't convert a string into a Date , but it can convert a pywintypes.Time object, or an integer representing the number of seconds since the Unix epoch. Hence the error: When the first argument is implicitly converted to a Time, the constructor complains that it needs an integer.
#start date: 12/31/1969 7:00:00 PM
str_Free_Busy_Data = obj_Recipient.FreeBusy(0, 11)
There are a number of ways to get the Unix timestamp from a date. See Convert python datetime to epoch with strftime.

Convert Unix Timestamp to human format in Django with Python

I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks.
edit
I'm using the python function time.time() to generate the timestamp. According to the doc:
time.time()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that
even though the time is always
returned as a floating point number,
not all systems provide time with a
better precision than 1 second. While
this function normally returns
non-decreasing values, it can return a
lower value than a previous call if
the system clock has been set back
between the two calls.
import datetime
datestring = "1277722499.82"
dt = datetime.datetime.fromtimestamp(float(datestring))
print(dt)
2010-06-28 11:54:59.820000

Categories

Resources