Date Time Formats in Python - python

What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?
2013-07-12T07:00:00Z
2013-07-10T11:00:00.000Z
Thanks in advance

That extra .000 is micro seconds.
This will convert a date string of a format to datetime object.
import datetime
d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
Then convert them into any format depending on your requirement, by using:
new_format = "%Y-%m-%d"
d1.strftime(new_format)

perhaps use .isoformat()
string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z specifies "zulu" time or UTC.
You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
You can remove the microseconds by change the microseconds value to 0:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt

you can try to trim the string
data = "2019-10-22T00:00:00.000-05:00"
result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")

use datetime module.
For a variable
import datetime
def convertDate(d):
new_date = datetime.datetime.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
return new_date.date()
convertDate("2019-12-23T00:00:00.000Z")
you can change the ".date()" to ".year", ".month", ".day" etc...
Output: # is now a datetime object
datetime.date(2019, 12, 23)
For a DataFrame column, use apply()
df['new_column'] = df['date_column'].apply(convertDate)

* Short and best way:
str(datetime.datetime.now()).replace(' ','T')
or
str(datetime.datetime.now()).replace(' ','T') + "Z"

Related

Converting timezone to new format and inserting into list in python [duplicate]

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).
What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?
>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026
I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.
Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
In Python 3.6:
from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'
https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat
This is the way I do it. ISO format:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'
You can replace the 'T' if you don't want ISO format:
datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'
Yet another option:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'
By default this uses local time, if you need UTC you can use the following:
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'
Keep the first 19 characters that you wanted via slicing:
>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'
I usually do:
import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0) # To print now without microsecond.
# To print now:
print(now)
output:
2019-01-13 14:40:28
Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:
unicode(datetime.datetime.now()).partition('.')[0]
As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.
isoformat(timespec='seconds', sep=' ')
Usage:
>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'
We can try something like below
import datetime
date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
f-string formatting
>>> import datetime
>>> print(f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}')
2021-12-01 22:10:07
This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-
import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
moment.hour, moment.minute, moment.second))
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
You can also use the following method
import datetime as _dt
ts = _dt.datetime.now().timestamp()
print("TimeStamp without microseconds: ", int(ts)) #TimeStamp without microseconds: 1629275829
dt = _dt.datetime.now()
print("Date & Time without microseconds: ", str(dt)[0:-7]) #Date & Time without microseconds: 2021-08-18 13:07:09
Current TimeStamp without microsecond component:
timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]

How do I convert YYYYMMDD to datetime, but maintain the same format

I have an variable integer that is in the format YYYYMMDD.
How do i convert that variable to datetime while maintaining the format of YYYYMMDD?
date = 20200930
nextday = date + 1
How do i fix this, so the nextday variable displays as 20201001
If I'm understanding what you need to do correctly, you can easily do it using the datetime package.
First, convert your variable to a date:
import datetime
date = 20200930
dt = datetime.datetime.strptime(str(date), '%Y%m%d')
Now, when you print this, you will see:
datetime.datetime(2020, 9, 30, 0, 0).
You can then add a day to it:
dt_new = dt + datetime.timedelta(1)
And specify the format you want to see the new date variable in:
print ('{date: %Y%m%d}'.format(date=dt_new))
which will give:
20201001.

python json date object to python datetime

I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'

Easier way to create date object from string

I'm working on an image upload utility, and part of the functionality is to parse the IPTC and EXIF data of the images.
IPTCInfo gets the information I need, but the date fields are in the format 20130925.
Now, I can break that integer up into 2013 09 25 and create a date object. Before I do so, is there already existing functionality to solve this issue?
The date class doesn't have a string-parsing function, but the datetime class does, strptime.
So, first make a datetime, then extract the date part of it:
>>> s = '20130925'
>>> dt = datetime.datetime.strptime(s, '%Y%m%d')
>>> d = dt.date()
>>> d
datetime.date(2013, 9, 25)
If you don't understand where the '%Y%m%d' comes from, see strftime() and strptime() Behavior.
You can use datetime.strptime:
>>> import datetime
>>> datetime.datetime.strptime("20130925","%Y%m%d").date()
datetime.date(2013, 9, 25)

How do you create numpy.datetime64 object from a unix timestamp and set the timezone to UTC?

I have a process where I read in a bunch of strings in ISO 8601 format at Zulu or UTC time. For example,
2012-06-20T21:15:00Z
2012-06-20T21:16:00Z
2012-06-20T21:17:00Z
2012-06-20T21:18:00Z
I convert the strings into timezone aware python datetime objects and then save them in a binary format as integers by converting them to Unix Timestamps. For example,
dt_str = '2012-06-20T21:15:00Z'
ts = int(mktime(datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%SZ').timetuple()))
# ts = 1340241300
When I read these timestamps back into another process I would like to instantiate a numpy.datetime64 object directly from the timestamp. The problem is that datetime64 sets the timezone to my local timezone.
np_dt = np.datetime64(ts,'s')
# np_dt = numpy.datetime64('2012-06-20T21:15:00-0400')
Does anyone know of a way that I could read in my timestamp so that it is UTC time? Would I would like for np_dt to equal is numpy.datetime64('2012-06-20T21:15:00-0000')...I think.
Regards
What about setting the timezone for your code.
import os, time
os.environ['TZ'] = 'GMT'
time.tzset()
# then your code
np_dt = np.datetime64(ts,'s')
You can use the dateutil module to help out. First, create a datetime object from the timestamp integer you saved:
>>> ts = 1340241300
>>> import datetime
>>> from dateutil import tz
>>> dt = datetime.datetime.fromtimestamp(ts).replace(tzinfo=tz.tzutc())
>>> dt
datetime.datetime(2012, 6, 20, 21, 15, tzinfo=tzutc())
Then pass it to numpy, which will convert it to the local timezone (I am in -4):
>>> import numpy as np
>>> np.datetime64(dt.isoformat())
numpy.datetime64('2012-06-20T17:15:00-0400')
Judging by the documentation, the only way to do it is to create it from a string that specifies the time zone directly. Thus you'll need to create a datetime.datetime object first and format it to a string with 'Z' appended, then construct the numpy.datetime64 from that.

Categories

Resources