You must be a U.S. citizen or resident alien (or be treated as a resident alien) to take the credit. Generally, you cannot take the credit if you were a nonresident alien at any time during the tax year.
Exceptions. You may be able to take the credit if you are a nonresident alien who is married to a U.S. citizen or resident alien at the end of the tax year and you and your spouse choose to treat you as a U.S. resident alien. If you make that choice, both you and your spouse are taxed on your worldwide incomes.
If you were a nonresident alien at the beginning of the year and a resident alien at the end of the year, and you were married to a U.S. citizen or resident alien at the end of the year, you may be able to choose to be treated as a U.S. resident alien for the entire year. In that case, you may be allowed to take the credit.
For information on these choices, see chapter 1 of Publication 519, U.S. Tax Guide for Aliens.