Time tuple to a datetime - python

I am trying to convert a timestamp tuple from dpkt to a datetime instance.
The timestamp looks like (seconds, microseconds). This is what I am currently doing, but it seems overkill:
from datetime import datetime as dt
ts = (1296770576, 247792)
ts_list = [str(item) for item in ts]
ts_list[1] = ts_list[1].zfill(6) #make sure we have 6 digits
ts_str = ".".join(ts_list)
ts_float = float(ts_str)
ts_dt = dt.fromtimestamp(ts_float)
Is there a simpler way?

Just use the seconds part, then update the datetime object with the microseconds part, using the .replace() method:
dt.fromtimestamp(ts[0]).replace(microsecond=ts[1])
Demo:
>>> from datetime import datetime as dt
>>> ts = (1296770576, 247792)
>>> dt.fromtimestamp(ts[0]).replace(microsecond=ts[1])
datetime.datetime(2011, 2, 3, 23, 2, 56, 247792)
If you did ever have to convert your (seconds, microseconds) tuple to a float timestamp, just use floating-point division instead:
>>> ts_float = float(ts[0]) + float(ts[1]) / 1000000
>>> dt.fromtimestamp(ts_float)
datetime.datetime(2011, 2, 3, 23, 2, 56, 247792)

Related

Python: How to compare date string in ISO 8601 format with current time

date_str = '2022-03-29T17:49:35.914417-04:00'
How to compare above date string with current date time?
Try using datetime.fromisoformat(date_string) to parse date_str and then passing the determined timezone info into datetime.now(tz=None):
>>> from datetime import datetime
>>> date_str = '2022-03-29T17:49:35.914417-04:00'
>>> dt = datetime.fromisoformat(date_str)
>>> dt
datetime.datetime(2022, 3, 29, 17, 49, 35, 914417, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now = datetime.now(dt.tzinfo)
>>> dt_now
datetime.datetime(2022, 5, 20, 15, 50, 58, 525908, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now > dt
True
>>> dt_now - dt
datetime.timedelta(days=51, seconds=79282, microseconds=611491)

Filter time array in python with datetime library

I want to filter my list of time string elements with the help of python datetime library.
I have a array like -
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
I want to make it be filtered from the ascending order (0:0:0 - 23:59:59) accordingly.
Also i will have bulk of data (array should be almost containing more than 5k ) so what will be most efficient for this?
How can i achieve this in python?
the resulting array should be something like -
["0:0:16","2:50:32","3:59:9","20:30:12","23:46:52"]
This will convert the strings to datetime, sort them then output a list with your desired format.
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
sorted(time_Arr, key=lambda x: datetime.strptime(x, '%H:%M:%S'))
['0:0:16', '2:50:32', '3:59:9', '20:30:12', '23:46:52']
Use datetime to parse the time then sort:
from datetime import datetime
time_Arr = ["0:0:16","3:59:9","2:50:32","23:46:52","20:30:12"]
time_Arr = sorted([datetime.strptime(t, "%H:%M:%S") for t in time_Arr])
# [datetime.datetime(1900, 1, 1, 0, 0, 16),
# datetime.datetime(1900, 1, 1, 2, 50, 32),
# datetime.datetime(1900, 1, 1, 3, 59, 9),
# datetime.datetime(1900, 1, 1, 20, 30, 12),
# datetime.datetime(1900, 1, 1, 23, 46, 52)]
from datetime import datetime
sorted([datetime.strptime(time, "%H:%M:%S") for time in time_Arr])

Convert integer date format to human readable format

I have a date time format where dates are represented as integers from 1/1/1900 .
For example: 1 is 1/1/1900 and 42998 is 20/9/2017.
How can I convert this format to a human readable format like dd/mm/yyyy ? I checked datetime documentation but I did not find any way to do this. I want to do this either on python 3 or 2.7.
Thanks for any suggestion.
You can define your dates as offsets from your basetime and construct a datetime:
In[22]:
import datetime as dt
dt.datetime(1900,1,1) + dt.timedelta(42998)
Out[22]: datetime.datetime(2017, 9, 22, 0, 0)
Once it's a datetime object you can convert this to a str via strftime using whatever format you desire:
In[24]:
(dt.datetime(1900,1,1) + dt.timedelta(42998-1)).strftime('%d/%m/%Y')
Out[24]: '21/09/2017'
So you can define a user func to do this:
In[27]:
def dtToStr(val):
base = dt.datetime(1900,1,1)
return (base + dt.timedelta(val-1)).strftime('%d/%m/%Y')
dtToStr(42998)
Out[27]: '21/09/2017'
import datetime
base_date = datetime.datetime(1900, 1, 1)
convert = lambda x: base_date + datetime.timedelta(days=x-1)
>>> convert(42998)
datetime.datetime(2017, 9, 21, 0, 0)
You can use a datetime object to do that.
import datetime
d = datetime.datetime(1900, 1, 1, 0, 0)
d + datetime.timedelta(days = 42998)
>> datetime.datetime(2017, 9, 22, 0, 0)

Convert a Date in String Format to a datetime.date

I have some strings which come to me in formats like
29-Jul-2014 or 03-Aug-2015
What is the easiest way to convert this to a datetime.date object?
I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...} and then do
dt = datetime.date(year, d[month], day)
Is there any other easier way and avoid the creation of this dictionary?
Thanks
Use datetime.datetime.strptime to convert the string to datetime.datetime object.
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)
Then, use datetime.datetime.date method to convert it to datetime.date object:
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
The easy way is use dateutil.parse module, it lets to parse the common date formats, even if you don't know what it is using currently
Ex:
>>> import dateutil.parser
>>>
>>> utc_time = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)
Once you have a datetime object, you only should invoke the datetime.date() method

Extracting time from a line in Python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting string into datetime
I got log entries like:
2013-01-09 06:13:51,464 DEBUG module 159 Djang...
What is the shortest (best) way to extract the date from this string?
Do you need to keep the microsecond?
>>> import re
>>> log = "2013-01-09 06:13:51,464 DEBUG module"
>>> p = re.compile("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d*")
>>> time_str = p.findall(log)[0]
>>> time_str
'2013-01-09 06:13:51,464'
>>> from datetime import datetime
>>> date_time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S,%f')
>>> date_time
datetime.datetime(2013, 1, 9, 6, 13, 51, 464000)
from datetime import datetime
val = '2013-01-09 06:13:51,464'.split(',')[0] # Remove milliseconds
date_object = datetime.strptime(val, '%Y-%m-%d %H:%M:%S')
>>> a = "2013-01-09 06:13:51,464 DEBUG module"
>>> a = a.split(" ")
>>> date,time = a[0], a[1]
>>> date = date.split("-")
>>> time = time.split(",")[0].split(":")
>>> date
['2013', '01', '09']
>>> time
['06', '13', '51']
>>> args_list = [int(i) for i in date]
>>> args_list.extend( [int(i) for i in time])
>>> args_list
[2013, 1, 9, 6, 13, 51]
>>> import datetime
>>> datetime.datetime(*args_list)
datetime.datetime(2013, 1, 9, 6, 13, 51)

Categories

Resources