Convert integer date format to human readable format - python

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)

Related

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])

Python - Convert Month Name to Integer

How can I convert 'Jan' to an integer using Datetime? When I try strptime, I get an error time data 'Jan' does not match format '%m'
You have an abbreviated month name, so use %b:
>>> from datetime import datetime
>>> datetime.strptime('Jan', '%b')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.strptime('Aug', '%b')
datetime.datetime(1900, 8, 1, 0, 0)
>>> datetime.strptime('Jan 15 2015', '%b %d %Y')
datetime.datetime(2015, 1, 15, 0, 0)
%m is for a numeric month.
However, if all you wanted to do was map an abbreviated month to a number, just use a dictionary. You can build one from calendar.month_abbr:
import calendar
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
Demo:
>>> import calendar
>>> abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
>>> abbr_to_num['Jan']
1
>>> abbr_to_num['Aug']
8
This is straightforward enough that you could consider just using a dictionary, then you have fewer dependencies anyway.
months = dict(Jan=1, Feb=2, Mar=3, ...)
print(months['Jan'])
>>> 1
Off the cuff-
Did you try %b?
from calendar import month_abbr
month = "Jun"
for k, v in enumerate(month_abbr):
if v == month:
month = k
break
print(month)
6
You will get the number of month 6

Create a parse function for different date formats in Python

I want to create a parse function with lambda able to recognize two different formats
"2014-01-06 15:23:00"
and
"2014-01-06"
The idea is to use this function to create a pandas dataframe but in some of the values the hour is missing
This is my first idea
parse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') if x is True else pd.datetime.strptime(x, '%Y-%m-%d')
it seems that x is True is not correct
Any idea??
dateutil has a parser that handles multiple formats:
>>> dateutil.parser.parse('2015-07-04')
datetime.datetime(2015, 7, 4, 0, 0)
>>> dateutil.parser.parse('2015-07-04 11:23:00')
datetime.datetime(2015, 7, 4, 11, 23)
>>> dateutil.parser.parse('2015-07-04T11:23:56')
datetime.datetime(2015, 7, 4, 11, 23, 56)
Even non iso formats like this
>>> dateutil.parser.parse('5-6-15')
datetime.datetime(2015, 5, 6, 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

Time tuple to a datetime

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)

Categories

Resources