Convert date to json date string in python - python

I have a list of dates (mm-yyyy), having only the fields of months and years:
d = ['09-2007', '10-2007', '03-2011', '05-2011']
And I need to convert them into JSON date strings..like 1154476800000.. will Python's datetime or simplejson module help in this?

In [30]: import datetime as DT
In [31]: import time
In [32]: d = ['09-2007', '10-2007', '03-2011', '05-2011']
In [33]: [time.mktime(DT.datetime.strptime(dstr, '%m-%Y').timetuple())*1000 for dstr in d]
Out[33]: [1188619200000.0, 1191211200000.0, 1298955600000.0, 1304222400000.0]

You need to convert those months to date objects, then to time values:
from datetime import datetime
import time
def to_jstimestamp(dt):
dt = datetime.strptime(dt, '%m-%Y')
return time.mktime(dt.timetuple()) * 1000
d = [to_jstimestamp(dt) for dt in d]
JSON does not have a standard for representing datetime values; what you are describing are JavaScript timestamps instead.
Demo:
>>> json.dumps([to_jstimestamp(dt) for dt in d])
'[1188601200000.0, 1191193200000.0, 1298937600000.0, 1304204400000.0]'

Related

How to convert date to datetime in python

Code:
def func(y, m):
for i in range(1, calendar.monthrange(y, m)[1]+1):
th_date = date(y, m, i)
print(th_date)
func(2020,4)
Note:
i am getting dates as date format i want to convert it into datetime i don't want time
You might just use datetime in place of date as 4th and following arguments to datetime.datetime are optional, so
import datetime
dt = datetime.datetime(2022,6,2)
print(dt)
gives output
2022-06-02 00:00:00
If you're not interested in time but you want to use the datetime module then you can use the date class. For example:
from datetime import date
def func(year, month, day=1):
return date(year, month, day)
print(func(2022, 4))
Output:
2022-04-01

How to add seconds (mili, nano, micro) to T/Z (ISO 8601) timestamp format?

Basically I have an entire dataframe with the timestamp in the following format:
2018-01-17T05:00:00.000000Z
And I'm looking to add different seconds on it (sometimes add 1 second, sometimes add 1 microsecond, etc).
The python datetime allows you to use milliseconds and microseconds.
>>> from datetime import datetime,timedelta
>>> dt = datetime.now()
>>> print(dt)
2019-07-05 17:21:49.523664
>>> dt1 = dt + timedelta(microseconds = 1,milliseconds = 1)
>>> print(dt1)
2019-07-05 17:21:49.524665
Regarding the nanoseconds you can find information here.
In case you have it as a string you have to transform it into datetime:
>>> from datetime import datetime,timedelta
>>> import dateutil.parser
>>> date = dateutil.parser.parse("2018-01-17T05:00:00.000000Z")
>>> print(date)
2018-01-17 05:00:00+00:00
>>> dt1 = date + timedelta(microseconds = 1,milliseconds = 1)
>>> print(dt1)
2018-01-17 05:00:00.001001+00:00
If you ask for the last part of the date +00:00, it is for the time zone you can remove it like this:
>>> dt1 = dt1.replace(tzinfo=None)
>>> print(dt1)
2018-01-17 05:00:00.001001
With Python 3.7 you may use datetime.fromisoformat:
import datetime
value = datetime.datetime.fromisoformat(str)
value += datetime.timedelta(seconds=1)
With older Python version you may use:
import datetime
value = datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%S.%fZ")
value += datetime.timedelta(seconds=1)

Python convert date to datetime

I have following string of date "2018-05-08" and I would like to convert it into the datetime format of python like: "2018-05-08T00:00:00.0000000". I understand I can combine the string like:
> date = "2018-05-08"
> time = "T00:00:00.0000000"
> date+time
'2018-05-08T00:00:00.0000000'
But is there pythonic way of doing it where I can use libraries like datetime?
You can use datetime module like this example:
import datetime
date = "2018-05-08"
final = datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S.%f')
print(final)
Output:
2018-05-08T00:00:00.000000
For more details visit datetime's documentation
Use this code
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())
from datetime import datetime
datetime.strftime(datetime.strptime('2018-05-08','%Y-%m-%d'),'%Y-%m-%dT%H:%M:%S.%f')
OUTPUT:
'2018-05-08T00:00:00.000000'
from datetime import datetime
date_as_datetime = datetime.strptime("2018-05-08", '%Y-%m-%d')
date_as_string = date_as_datetime.strftime('%Y-%m-%dT%H:%M:%S')
print(date_as_string)
Out:
'2018-05-08T00:00:00'
See strptime/strftime options here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Yes, you can use the datetime module and the strftime method from that module. Here is an example below if we want to format the current time.
import datetime
current_time = datetime.datetime.now()
formatted_time = datetime.datetime.strftime(current_time, "%Y-%h-%d %H:%m:%S")
print(formatted_time)
Here is the output:
2018-May-08 13:05:16

How to get year from a file, column containing datetime

this is what I am doing to get year(1880) from year column(year: 01/01/1880 12:00:00 AM),
import pandas
from datetime import date, datetime, timedelta
data = pandas.read_csv('Landings.csv')
a=data['year']
years = **datetime.datetime.a**
print years
I think the hightlited line is creating probnem anyone correct me, how to get year
I guess data["year"] returns a Series of strings, rather than a string, hence you need to apply/map a parser to to.
import pandas as pd
from datetime import datetime
data = pd.read_csv("Landings.csv")
a=data["year"]
years = [datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]
Alternatively. A more pandas-esque solution (basically, use the pandas.Series.applymethod instead of the list generator). This will leave you in the realm of numpy/pandas
years = data["year"].apply(lambda date: datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year)
Example
In [1]: import pandas as pd
In [2]: from datetime import datetime
In [3]: data = pd.DataFrame({"year": ["01/01/1880 12:00:00 AM"]})
In [4]: data
Out[4]:
year
0 01/01/1880 12:00:00 AM
In [5]: a = data["year"]
In [6]: [datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]
Out[6]: [1880]
Since 'a' is a string, it is not a callable function in the datetime module. The following code should work.
import pandas
from datetime import date, datetime, strptime, timedelta
data = pandas.read_csv('Landings.csv')
a=data['year']
years = datetime.strptime(a, '%m/%d/%Y %H:%M:%S %p').year
print years

Split List based on index of value

Assuming I have a list of dates:
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
I want to split the 'dates' list based on this 'test' variable
Desired output:
1. ['11/09/2013','12/09/2013','20/09/2013']
2. ['27/09/2013','30/09/2013']
If 'test' actually belongs(contains) in the list, it must be in list 1.
I'm trying everything still no luck.
You should convert the strings into datetime objects and then split the list using a date comparison:
from datetime import datetime
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
# Convert to datetime objects
dd = [datetime.strptime(d,'%d/%m/%Y') for d in dates]
tt = datetime.strptime(test,'%d/%m/%Y')
# Split lists
dd_before = [d for d in dd if d < tt]
dd_after = [d for d in dd if d >= tt]
# Convert back to strings if needed
dates_before = [datetime.strftime(d,'%d/%m/%Y') for d in dd_before]
dates_after = [datetime.strftime(d,'%d/%m/%Y') for d in dd_after]
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
dates.append(test)
dates.sort()
index = dates.index(test)
print dates[:index]
print dates[index + 1:]
output
['11/09/2013', '12/09/2013', '20/09/2013']
['27/09/2013', '30/09/2013']
You can get your desired result.
How about converting the items to datetime objects?
from datetime import datetime
# convert to datetime objects
datesdt = [datetime.strptime(date, '%d/%m/%Y') for date in dates]
testdt = datetime.strptime(test, '%d/%m/%Y')
# make separate datetime object lists for low and high dates
low_date_dt_list = [dt for dt in datesdt if dt <= testdt]
high_date_dt_list = [dt for dt in datesdt if dt > testdt]
# now print in desired format
low_date_list = [dt.strftime('%d/%m/%Y') for dt in low_date_dt_list]
high_date_list = [dt.strftime('%d/%m/%Y') for dt in high_date_dt_list]
Here's what I get for output when using the above code with your given dates and test values:
In [27]: low_date_list
Out[27]: ['11/09/2013', '12/09/2013', '20/09/2013']
In [28]: high_date_list
Out[28]: ['27/09/2013', '30/09/2013']
Documentation for datetime.strptime
Datetime Format Codes
Documentation for strftime

Categories

Resources