The output of
/sbin/hwclock --show --utc
looks like
2017-06-01 16:04:47.029482+1:00
How to parse this string into a datetime object in Python?
You can use the third party library python-dateutil (pip install python-dateutil):
>>> import dateutil.parser
>>> dateutil.parser.parse('2017-06-01 16:04:47.029482+1:00')
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=tzoffset(None, 3600))
If you don't want to use a third party library:
import datetime
import re
def parse_iso_timestamp(clock_string):
# Handle offset < 10
clock_string = re.sub(r'\+(\d):', r'+0\1', clock_string)
# Handle offset > 10
clock_string = re.sub(r'\+(\d\d):', r'+\1', clock_string)
# Parse
dt = datetime.datetime.strptime(clock_string, '%Y-%m-%d %H:%M:%S.%f%z')
return dt
print(parse_iso_timestamp('2017-06-01 16:04:47.029482+1:00').__repr__())
print(parse_iso_timestamp('2017-06-01 16:04:47.029482+10:00').__repr__())
Which outputs:
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 36000)))
using just datetime:
import datetime
s = "2017-06-01 16:04:47.029482+1:00"
try:
stamp, zone = s.rsplit('+', 1)
sign = '+'
except ValueError:
stamp, zone = s.rsplit('-', 1)
sign = '-'
zone = int(zone.replace(':', ''))
new_s = '%s%s%04d' % (stamp, sign, zone)
print(new_s)
dt = datetime.datetime.strptime(new_s, "%Y-%m-%d %H:%M:%S.%f%z")
print(dt.__repr__())
You can parse a string into datetime object using datetime.strptime(). It takes the date string and format as input and return datetime object method.
split by space fist value is date like 2017-06-01
d =date.split(" ")[0]
split by dot to get time
t = data.split(" ")[1].split(".")[0]
Related
I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value
You may try this way :
from datetime import datetime
date_str = '2016-04-15T12:24:20.707Z'
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(date)
Output:
2016-04-15 12:24:20.707000
You have to specify the format as "%Y-%m-%dT%H:%M:%S.%fZ" while conversion
In [11]: from datetime import datetime
In [12]: out_format = "%Y-%m-%d"
In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ"
In [14]: date_time_obj = datetime.strptime(time,input_format)
In [15]: date_time_obj
Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000)
In [16]: date_time_str = date_time_obj.strftime(out_format)
In [17]: date_time_str
Out[17]: '2016-04-15'
import dateutil.parser
from datetime import datetime
dt = dateutil.parser.parse('2016-04-15T12:24:20.707Z')
This seems to be working alright:
import dateparser
dateparser.parse('2016-04-15T12:24:20.707Z')
> datetime.datetime(2016, 4, 15, 12, 24, 20, 707000, tzinfo=<StaticTzInfo 'Z'>)
Probably iso8601 package is what you need
You may try this way if you need something on the fly:
This returns the current datetime in UTC, as a datetime object then immediately converts it to your preferred custom format.
from datetime import datetime, timezone
from time import strftime
# Get UTC Time datetime object and convert it to your preferred format.
print(f"Regular : { datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') }") # Regular : 2022-06-04 23:08:27
print(f"Log Format: { datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') }") # Log Format: 20220604_230827
print(f"YMD Format: { datetime.now(timezone.utc).strftime('%Y-%m-%d') }") # YMD Format: 2022-06-04
print(f"Time Format: { datetime.now(timezone.utc).strftime('%H:%M:%S') }") # Time Format: 23:08:27
# Without the f'String'
print(datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) # Regular : 2022-06-04 23:08:27
print(datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')) # Log Format: 20220604_230827
print(datetime.now(timezone.utc).strftime('%Y-%m-%d')) # YMD Format: 2022-06-04
print(datetime.now(timezone.utc).strftime('%H%M%S')) # Time Format: 23:08:27
# Details:
# Get current DateTime in UTC
datetime.now(timezone.utc)
# datetime.datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=datetime.timezone.utc)
type(datetime.now(timezone.utc))
# <class 'datetime.datetime'>
# Use the strftime on the datetime object directly
datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
# '2022-06-04 23:13:27'
type(datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S'))
# <class 'str'>
Given the following Python datetime object representing an UTC time:
2016-09-15 22:13:03-2:00
I'm trying to obtain the corresponding local time datetime, where the UTC offset is applied:
2016-09-15 20:13:03
I was hoping to find a method in the datetime module that was able to do this, but I did not succeed. Any help is very appreciated.
Regards
I do not know if this is the best answer but here is what I have for you. Typically I would not do this since it is better to use the UTC time and convert
Here is a example:
value = datetime.datetime.strptime(str(utc_datetime), '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)
value = value.astimezone(pytz.timezone("America/Los_Angeles"))
I was unable to use your datetime as the syntax is a bit off so I went ahead and used dateutil.parser to convert it to a datetime object
>>> from dateutil.parser import parse
>>> val = parse('2016-09-15 22:13:03-2:00')
There are other ways to set a datetime object to UTC but I find pytz to be the easiest
>>> import pytz
>>> utc_val = val.replace(tzinfo=pytz.utc)
Here is the output of those two values. From here I grab the delta and subtract it
>>> val, utc_val
(datetime.datetime(2016, 9, 15, 22, 13, 3, tzinfo=tzoffset(None, -7200)), datetime.datetime(2016, 9, 15, 22, 13, 3, tzinfo=<UTC>))
>>>
>>> delta = val - utc_val
I remove the tzinfo since this is a converted datetime value
>>> local_dt = (val - delta).replace(tzinfo=None)
>>> local_dt
datetime.datetime(2016, 9, 15, 20, 13, 3)
>>> str(local_dt)
'2016-09-15 20:13:03'
I have a time which is 13:11:06 and i want to -GMT (i.e -0530). I can minus it by simply doing -5 by splitting the string taking the first digit (convert to int) and then minus it and then re-join. But then i get it in a format which is 8:11:06 which is not right as it should be 08:11:06, secondly its a lengthy process. Is there a easy way to get my time in -GMT format (08:11:06)
This is what i did to get -GMT time after getting the datetime
timesplithour = int(timesplit[1]) + -5
timesplitminute = timesplit[2]
timesplitseconds = timesplit[3]
print timesplithour
print timesplitminute
print timesplitseconds
print timesplithour + ":" + timesplitminute + ":" + timesplitseconds
You could use Python's datatime library to help you as follows:
import datetime
my_time = "13:11:06"
new_time = datetime.datetime.strptime("2016 " + my_time, "%Y %H:%M:%S") - datetime.timedelta(hours=5, minutes=30)
print new_time.strftime("%H:%M:%S")
This would print:
07:41:06
First it converts your string into a datetime object. It then creates a timedelta object allowing you to subtract 5 hours 30 minutes from the datetime object. Finally it uses strftime to format the resulting datetime into a string in the same format.
Use the datetime module:
from datetime import datetime, timedelta
dt = datetime.strptime('13:11:06', '%H:%M:%S')
time_gmt = (dt - timedelta(hours=5, minutes=30)).time()
print(time_gmt.hour)
print(time_gmt.minute)
print(time_gmt.second)
s = time_gmt.strftime('%H:%M:%S')
print(s)
Output
7
41
6
07:41:06
Note that this subtracts 5 hours and 30 minutes as initially mentioned in the question. If you really only want to subtract 5 hours, use timedelta(hours=5).
You can use datetimes timedelta.
print datetime.datetime.today()
>>> datetime.datetime(2016, 3, 3, 10, 45, 6, 270711)
print datetime.datetime.today() - datetime.timedelta(days=3)
>>> datetime.datetime(2016, 2, 29, 10, 45, 8, 559073)
This way you can subtract easily
Assuming the time is a datetime instance
import datetime as dt
t = datetime(2015,12,31,13,11,06)
#t.time() # gives time object. ie no date information
offset = dt.timedelta(hours=5,minutes=30) # or hours=5.5
t -= offset
t.strftime(("%H:%M:%S") # output as your desired string
#'18:41:06'
If the object is datetime and you don't care about DST, the simplest thing you can do is,
In [1]: from datetime import datetime
In [2]: curr = datetime.now()
In [3]: curr
Out[3]: datetime.datetime(2016, 3, 3, 9, 57, 31, 302231)
In [4]: curr.utcnow()
Out[4]: datetime.datetime(2016, 3, 3, 8, 57, 57, 286956)
I get the date and time as string like 2014-05-18T12:19:24+04:00
I found another question explaining how to handle dates in UTC timezone (2012-05-29T19:30:03.283Z)
What should I do with +04:00 in my case (if I want to store time in UTC timezone in Python)?
Upd. I've tried to parse it like below:
dt = '2014-05-19T14:48:50+04:00'
plus_position = dt.find('+') # remove column in the timezone part
colon_pos = dt.find(':', plus_position)
dt = dt[:colon_pos] + dt[colon_pos+1:]
dt = datetime.datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S%z') # '2014-05-19T14:48:50+0400'
But it fails - 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'
Using dateutil:
>>> import dateutil.parser
>>> dateutil.parser.parse('2014-05-18T12:19:24+04:00')
datetime.datetime(2014, 5, 18, 12, 19, 24, tzinfo=tzoffset(None, 14400))