PostgreSQL convert month name to number

吃可爱长大的小学妹 提交于 2019-12-12 19:27:17

问题


I have a query that returns a field as month and year for example "Nov 2015" I want to get the number for the month, here I have to get number as "11".


回答1:


You can use the to_date function that can parse input in a certain format into a 'real' date. Then with this date you can extract the month from it.

select EXTRACT(MONTH FROM to_date('Nov 2015', 'Mon YYYY'))

See http://www.postgresql.org/docs/current/static/functions-formatting.html for the formatting syntax and http://www.postgresql.org/docs/current/static/functions-datetime.html for the other datetime functions etc..




回答2:


to_char()

select to_char(to_date('Nov 2015', 'Mon YYYY'), 'mm') month_no

and the query can be

select to_char(to_date(your_date_col, 'Mon YYYY'), 'mm') month_no
from table_name



回答3:


You can use the function to_timestamp(text, text) and extract(field from timestamp):

SELECT EXTRACT(MONTH FROM TO_TIMESTAMP("Nov 2015", "Mon YYYY"));

see the documentation for to_timestamp and extract




回答4:


If your date is timestamp , for example:"2017-01-24 23:00:00-03" (this is timestamp with time zone)

select to_char(your_date, 'MM') from your_table

Then the result would be in this case: "01"



来源:https://stackoverflow.com/questions/33912060/postgresql-convert-month-name-to-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!