python-datetime

Convert string into datetime.time object

北战南征 提交于 2019-11-27 11:02:13
问题 Given the string in this format "HH:MM" , for example "03:55" , that represents 3 hours and 55 minutes . I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that? 回答1: Use datetime.datetime.strptime() and call .time() on the result: >>> datetime.datetime.strptime('03:55', '%H:%M').time() datetime.time(3, 55) The first argument to .strptime() is the string to parse, the second is the expected format. 回答2: >>> datetime.time(*map(int, '03:55'

Getting today's date in YYYY-MM-DD in Python?

爷,独闯天下 提交于 2019-11-27 10:03:59
I'm using: str(datetime.datetime.today()).split()[0] to return today's date in the YYYY-MM-DD format. Is there a less crude way to achieve this? You can use strftime : from datetime import datetime datetime.today().strftime('%Y-%m-%d') Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples ) datetime.today().strftime('%Y-%m-%d-%H:%M:%S') There's even simpler way than the accepted answer; valid both for Python 2 & 3. from datetime import date today = str(date.today()) print(today) # '2017-12-26' Datetime is just lovely if you

Converting string date to timestamp in python 3.4

旧时模样 提交于 2019-11-27 08:35:17
问题 I am trying to convert string date to timestamp in Python as described in the post here. When I run the code examples in the post, I encounter an error. For e.g.: >>> import time >>> import datetime >>> s = "01/12/2011" >>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()) File "C:\Python34\lib\_strptime.py", line 15, in <module>

Pandas dataframe datetime to time then to seconds

与世无争的帅哥 提交于 2019-11-27 07:24:52
问题 I have a dataframe. A column contains timestamps. I would like to remove dates and convert the time to seconds. First I converted them to datetime: In: df_time = pd.to_datetime(df["Timestamp"]) Out: 0 2017-11-07 13:09:00 1 2017-11-07 13:11:00 2 2017-11-07 13:13:00 3 2017-11-07 13:15:00 dtype: datetime64[ns] Then I removed dates: In: df_time = pd.Series([val.time() for val in df_time]) Out: 0 13:09:00 1 13:11:00 2 13:13:00 3 13:15:00 4 13:17:00 dtype: object But they became objects and I did

How do I round datetime column to nearest quarter hour

扶醉桌前 提交于 2019-11-27 07:15:00
I have loaded a data file into a Python pandas dataframe. I has a datetime column of the format 2015-07-18 13:53:33.280 . What I need to do is create a new column that rounds this out to its nearest quarter hour. So, the date above will be rounded to 2015-07-18 13:45:00.000 . How do I do this in pandas? I tried using the solution from here , but get an 'Series' object has no attribute 'year' error. Assuming that your series is made up of datetime objects, You need to use Series.apply . Example - import datetime df['<column>'] = df['<column>'].apply(lambda dt: datetime.datetime(dt.year, dt

How do I determine if current time is within a specified range using Python's datetime module?

北慕城南 提交于 2019-11-27 05:40:46
问题 What would be the best way to see if the current time lies between say 10:30 AM and 4:30 PM . I could think of the following, not sure how correct: from datetime import datetime nw = datetime.now() hrs = nw.hour;mins = nw.minute;secs = nw.second; zero = timedelta(seconds = secs+mins*60+hrs*3600) st = nw - zero # this take me to 0 hours. time1 = st + timedelta(seconds=10*3600+30*60) # this gives 10:30 AM time2 = st + timedelta(seconds=16*3600+30*60) # this gives 4:30 PM if nw>= time1 or nw <=

Pandas: convert date in month to the 1st day of next month

限于喜欢 提交于 2019-11-26 21:35:16
问题 I am wondering if there are any efficient methods or one-liner that, given a pandas DatetimeIndex date1 , return a DatetimeIndex date2 that is the first day of the next month? For example, if date1 is '2011-09-30' then date2 is '2011-10-01'? I have tried this one liner df.index.to_period("M").to_timestamp('M') But this seems only able to return the "last day of the same month". Is it possible to do some datetime arithmetic here? Thanks! 回答1: You can use pd.offsets.MonthBegin() In [261]: d =

Python datetime strptime() and strftime(): how to preserve the timezone information

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 19:28:00
问题 See the following code: import datetime import pytz fmt = '%Y-%m-%d %H:%M:%S %Z' d = datetime.datetime.now(pytz.timezone("America/New_York")) d_string = d.strftime(fmt) d2 = datetime.datetime.strptime(d_string, fmt) print d_string print d2.strftime(fmt) the output is 2013-02-07 17:42:31 EST 2013-02-07 17:42:31 The timezone information simply got lost in the translation. If I switch '%Z' to '%z', I get ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z' I know I can use python

Getting today's date in YYYY-MM-DD in Python?

自古美人都是妖i 提交于 2019-11-26 17:54:36
问题 I'm using: str(datetime.datetime.today()).split()[0] to return today's date in the YYYY-MM-DD format. Is there a less crude way to achieve this? 回答1: You can use strftime: from datetime import datetime datetime.today().strftime('%Y-%m-%d') Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples) datetime.today().strftime('%Y-%m-%d-%H:%M:%S') 回答2: There's even simpler way than the accepted answer; valid both for Python 2 & 3.

Why is pandas.to_datetime slow for non standard time format such as &#39;2014/12/31&#39;

烈酒焚心 提交于 2019-11-26 15:52:16
问题 I have a .csv file in such format timestmp, p 2014/12/31 00:31:01:9200, 0.7 2014/12/31 00:31:12:1700, 1.9 ... and when read via pd.read_csv and convert the time str to datetime using pd.to_datetime , the performance drops dramatically. Here is a minimal example. import re import pandas as pd d = '2014-12-12 01:02:03.0030' c = re.sub('-', '/', d) %timeit pd.to_datetime(d) %timeit pd.to_datetime(c) %timeit pd.to_datetime(c, format="%Y/%m/%d %H:%M:%S.%f") and the performances are: 10000 loops,