Transform datetimes in python - python

How can I transform a string datetime like this:
"2018-07-13T00:00:00+00:00"
Into this?
"2018-07-13T00:00:00.000000+00:00"

try this out:
from datetime import datetime
datetime_string = "2018-07-13T00:00:00+00:00"
new_datetime_string = datetime.fromisoformat(datetime_string).isoformat(timespec="microseconds")
and for before python V3.7:
date_time = datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S%z').strftime("%Y-%m-%dT%H:%M:%S.%f%z")

Related

Issue with datetime string format

Im trying to convert a datetime object to a string but it does not seem to give me the desired output.
from datetime import datetime
cur_time = datetime.now()
last_runtime = cur_time.strftime("%Y-%m-%dT%H:%M:%S.%f+%Z")
print(last_runtime)
My current output:
2021-10-13T09:09:27.824592+
My desired output:
2021-10-13T09:09:27.825+00:00
You can use .astimezone() and small z on the format string:
from datetime import datetime
cur_time = datetime.now()
last_runtime = cur_time.astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
last_runtime = "{0}:{1}".format(
last_runtime[:-2],
last_runtime[-2:]
)
print(last_runtime)

How to convert datetime into GMT +7 in Python?

I have a dataframe that looks like that:
conversation__created_at
0 2020-10-15T03:39:42.766773+00:00
1 2020-10-14T11:24:33.831177+00:00
2 2020-10-14T08:29:44.192258+00:00
3 2020-10-14T01:42:06.674313+00:00
4 2020-10-13T12:57:04.218184+00:00
How to convert it into GMT +7?
I assume you have a pandas series because the data you posted looks like one.
Then you can use tz_convert, i.e.
import pandas as pd
pd.to_datetime('2020-10-15T03:39:42.766773+00:00').tz_convert('Etc/GMT+7')
As pointed out in the comments, since the datetime carries a T in it, it is of string format, thus we need to convert to datetime first and then convert to the correct timezone.
pd.to_datetime(series).dt.tz_convert('Etc/GMT+7')
You can use datetime library only.
from datetime import datetime, timedelta, timezone
d = datetime.fromisoformat("2020-10-15T03:39:42.766773+00:00")
tz = timezone(timedelta(hours=7))
new_time = d.astimezone(tz)
you can use pytz to set timezone for your datetime instance
for example:
from pytz import timezone
from datetime import datetime
date = datetime.now()
print(date)
tz = timezone("Etc/GMT+7")
date = date.replace(tzinfo=tz)
print(date)
out put:
2020-10-26 10:33:25.934699
2020-10-26 10:33:25.934699-07:00
You can apply pytz.timezone on the df
from pytz import timezone
from datetime import datetime
def myDate(x):
tz = timezone("Etc/GMT+7")
dt = x.replace(tzinfo=tz)
return dt
df['conversation__created_at'] = df.apply(lambda row: myDate(row['conversation__created_at'].to_pydatetime()))

How to convert string contains datetime in isoformat to date and time values?

I have the following string format (Python 3.6):
'2018-11-19T10:04:57.426872'
I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'
I tried to convert it with:
from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')
But this gives:
ValueError: unconverted data remains: T10:04:57.426872
In the above example I want to see:
start_date = '2018-11-19'
start_time = '10:04'
Since the date seems to be in ISO-Format, a simple
start = datetime.datetime.fromisoformat(text)
will parse it correctly. From there you can get your date and time with
start_date = start.strftime("%Y-%m-%d")
start_time = start.strftime("%H:%M")
Edit:
For Python < 3.7, you can use this format:
start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")
For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.
Try this:We have one of the best package for parsing dates called dateutil.
from dateutil import parser
date1='2018-11-19T10:04:57.426872'
print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
print 'Start_time:',parser.parse(date1).strftime("%H:%M")
Result:Start_date:2018-11-19
Start_time:10:04
You need to parse the entire string into one datetime object and then extract your required values from that.
dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
d = dt.date()
t = dt.time()
print(d.strftime('%Y-%m-%d'))
print(t.strftime('%H:%M'))
Which outputs:
2018-11-19
10:04

Python: Get date format as a string from datetime64[ns]

I want to determine the date format of an input datetime64[ns] value, and obtain a str.
Example:
input value = 1978-07-06
output value = '%Y-%m-%d'
I've tried this but got stuck:
import dateutil.parser
from datetime import datetime
yourdate = dateutil.parser.parse(input)
datetimeobject = datetime.strptime(yourdate,'%Y-%m-%d %H:%M:%S')
Any help on this would be appreciated.
Note: dateinfer gave me "No module named 'infer' " error
extract the date, from input using regular expression
import dateutil.parser
from datetime import datetime
input = '1978-07-06' # or - 06/07/1978
date_obj = dateutil.parser.parse(input)
date_string = date_obj.strftime('%Y-%m-%d %H:%M:%S')

How to convert string with timezone string to datetime?

I have a string like this: '2005-01-03 16:00:00:000 America/New_York', the simplest way to convert it to a datetime instance I could come up with is as below:
ts=r'2005-01-03 16:00:00:000 America/New_York'
import re
pos=re.match(r'[\d\- :]*', ts).end()
tzs=ts[pos:]
tss=ts[:pos-5]
from pytz import timezone
tz=timezone(tzs)
from dateutil import parser
dt=parser.parse(tss)
d=tz.localize(dt)
print d
#2005-01-03 16:00:00-05:00
which is too complicated I think....
So is there any simpler way to achieve this? Thx in advance ~
How about:
import datetime
import pytz
ts = '2005-01-03 16:00:00:000 America/New_York'
tPart, tzPart = ts.rsplit(' ', 1)
dt = datetime.datetime.strptime(tPart, "%Y-%m-%d %H:%M:%S:%f")
tz = pytz.timezone(tzPart)
d = tz.localize(dt)

Categories